1. 06 7月, 2016 4 次提交
    • E
      qapi: Add new clone visitor · a15fcc3c
      Eric Blake 提交于
      We have a couple places in the code base that want to deep-clone
      one QAPI object into another, and they were resorting to serializing
      the struct out to QObject then reparsing it.  A much more efficient
      version can be done by adding a new clone visitor.
      
      Since cloning is still relatively uncommon, expose the use of the
      new visitor via a QAPI_CLONE() macro that takes care of type-punning
      the underlying function pointer, rather than generating lots of
      unused functions for types that won't be cloned.  And yes, we're
      relying on the compiler treating all pointers equally, even though
      a strict C program cannot portably do so - but we're not the first
      one in the qemu code base to expect it to work (hello, glib!).
      
      The choice of adding a fourth visitor type deserves some explanation.
      On the surface, the clone visitor is mostly an input visitor (it
      takes arbitrary input - in this case, another QAPI object - and
      creates a new QAPI object during the course of the visit).  But
      ever since commit da72ab0 consolidated enum visits based on the
      visitor type, using VISITOR_INPUT would cause us to run
      visit_type_str(), even though for cloning there is nothing to do
      (we just copy the enum value across, without regards to its mapping
      to strings).   Also, since our input happens to be a QAPI object,
      we can also satisfy the internal checks for VISITOR_OUTPUT.  So in
      the end, I settled with a new VISITOR_CLONE, and chose its value
      such that many internal checks can use 'v->type & mask', sticking
      to 'v->type == value' where the difference matters.
      
      Note that we can only clone objects (including alternates) and lists,
      not built-ins or enums.  The visitor core hides integer width from
      the actual visitor (since commit 04e070d2), and as long as that's the
      case, we can't clone top-level integers.  Then again, those can
      always be cloned by direct copy, since they are not objects with
      deep pointers, so it's no real loss.  And restricting cloning to
      just objects and lists is cleaner than restricting it to non-integers.
      As such, I documented that the clone visitor is for direct use only
      by code internal to QAPI, and should not be used on incomplete objects
      (other than a hack to work around the fact that we allow NULL in place
      of "" in visit_type_str() in other output visitors).  Note that as
      written, the clone visitor will never fail on a complete object.
      
      Scalars (including enums) not at the root of the clone copy just fine
      with no additional effort while visiting the scalar, by virtue of a
      g_memdup() each time we push another struct onto the stack.  Cloning
      a string requires deduplication of a pointer, which means it can also
      provide the guarantee of an input visitor of never producing NULL
      even when still accepting NULL in place of "" the way the QMP output
      visitor does.
      
      Cloning an 'any' type could be possible by incrementing the QObject
      refcnt, but it's not obvious whether that is better than implementing
      a QObject deep clone.  So for now, we document it as unsupported,
      and intentionally omit the .type_any() callback to let a developer
      know their usage needs implementation.
      
      Add testsuite coverage for several different clone situations, to
      ensure that the code is working.  I also tested that valgrind was
      happy with the test.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1465490926-28625-14-git-send-email-eblake@redhat.com>
      Reviewed-by: NMarkus Armbruster <armbru@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      a15fcc3c
    • E
      qapi: Add new visit_complete() function · 3b098d56
      Eric Blake 提交于
      Making each output visitor provide its own output collection
      function was the only remaining reason for exposing visitor
      sub-types to the rest of the code base.  Add a polymorphic
      visit_complete() function which is a no-op for input visitors,
      and which populates an opaque pointer for output visitors.  For
      maximum type-safety, also add a parameter to the output visitor
      constructors with a type-correct version of the output pointer,
      and assert that the two uses match.
      
      This approach was considered superior to either passing the
      output parameter only during construction (action at a distance
      during visit_free() feels awkward) or only during visit_complete()
      (defeating type safety makes it easier to use incorrectly).
      
      Most callers were function-local, and therefore a mechanical
      conversion; the testsuite was a bit trickier, but the previous
      cleanup patch minimized the churn here.
      
      The visit_complete() function may be called at most once; doing
      so lets us use transfer semantics rather than duplication or
      ref-count semantics to get the just-built output back to the
      caller, even though it means our behavior is not idempotent.
      
      Generated code is simplified as follows for events:
      
      |@@ -26,7 +26,7 @@ void qapi_event_send_acpi_device_ost(ACP
      |     QDict *qmp;
      |     Error *err = NULL;
      |     QMPEventFuncEmit emit;
      |-    QmpOutputVisitor *qov;
      |+    QObject *obj;
      |     Visitor *v;
      |     q_obj_ACPI_DEVICE_OST_arg param = {
      |         info
      |@@ -39,8 +39,7 @@ void qapi_event_send_acpi_device_ost(ACP
      |
      |     qmp = qmp_event_build_dict("ACPI_DEVICE_OST");
      |
      |-    qov = qmp_output_visitor_new();
      |-    v = qmp_output_get_visitor(qov);
      |+    v = qmp_output_visitor_new(&obj);
      |
      |     visit_start_struct(v, "ACPI_DEVICE_OST", NULL, 0, &err);
      |     if (err) {
      |@@ -55,7 +54,8 @@ void qapi_event_send_acpi_device_ost(ACP
      |         goto out;
      |     }
      |
      |-    qdict_put_obj(qmp, "data", qmp_output_get_qobject(qov));
      |+    visit_complete(v, &obj);
      |+    qdict_put_obj(qmp, "data", obj);
      |     emit(QAPI_EVENT_ACPI_DEVICE_OST, qmp, &err);
      
      and for commands:
      
      | {
      |     Error *err = NULL;
      |-    QmpOutputVisitor *qov = qmp_output_visitor_new();
      |     Visitor *v;
      |
      |-    v = qmp_output_get_visitor(qov);
      |+    v = qmp_output_visitor_new(ret_out);
      |     visit_type_AddfdInfo(v, "unused", &ret_in, &err);
      |-    if (err) {
      |-        goto out;
      |+    if (!err) {
      |+        visit_complete(v, ret_out);
      |     }
      |-    *ret_out = qmp_output_get_qobject(qov);
      |-
      |-out:
      |     error_propagate(errp, err);
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1465490926-28625-13-git-send-email-eblake@redhat.com>
      Reviewed-by: NMarkus Armbruster <armbru@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      3b098d56
    • E
      qapi: Add new visit_free() function · 2c0ef9f4
      Eric Blake 提交于
      Making each visitor provide its own (awkwardly-named) FOO_cleanup()
      is unusual, when we can instead have a polymorphic visit_free()
      interface.  Over the next few patches, we can use the polymorphic
      functions to eliminate the need for a FOO_get_visitor() function
      for accessing specific visitor functionality, once everything can
      be accessed directly through the Visitor* interfaces.
      
      The dealloc visitor is the first one converted to completely use
      the new entry point, since qapi_dealloc_visitor_cleanup() was the
      only reason that qapi_dealloc_get_visitor() existed, and only
      generated and testsuite code was even using it.  With the new
      visit_free() entry point in place, we no longer need to expose
      the QapiDeallocVisitor subtype through qapi_dealloc_visitor_new(),
      and can get by with less generated code, with diffs that look like:
      
      | void qapi_free_ACPIOSTInfo(ACPIOSTInfo *obj)
      | {
      |-    QapiDeallocVisitor *qdv;
      |     Visitor *v;
      |
      |     if (!obj) {
      |         return;
      |     }
      |
      |-    qdv = qapi_dealloc_visitor_new();
      |-    v = qapi_dealloc_get_visitor(qdv);
      |+    v = qapi_dealloc_visitor_new();
      |     visit_type_ACPIOSTInfo(v, NULL, &obj, NULL);
      |-    qapi_dealloc_visitor_cleanup(qdv);
      |+    visit_free(v);
      |}
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1465490926-28625-5-git-send-email-eblake@redhat.com>
      Reviewed-by: NMarkus Armbruster <armbru@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      2c0ef9f4
    • E
      qapi: Add parameter to visit_end_* · 1158bb2a
      Eric Blake 提交于
      Rather than making the dealloc visitor track of stack of pointers
      remembered during visit_start_* in order to free them during
      visit_end_*, it's a lot easier to just make all callers pass the
      same pointer to visit_end_*.  The generated code has access to the
      same pointer, while all other users are doing virtual walks and
      can pass NULL.  The dealloc visitor is then greatly simplified.
      
      All three visit_end_*() functions intentionally take a void**,
      even though the visit_start_*() functions differ between void**,
      GenericList**, and GenericAlternate**.  This is done for several
      reasons: when doing a virtual walk, passing NULL doesn't care
      what the type is, but when doing a generated walk, we already
      have to cast the caller's specific FOO* to call visit_start,
      while using void** lets us use visit_end without a cast. Also,
      an upcoming patch will add a clone visitor that wants to use
      the same implementation for all three visit_end callbacks,
      which is made easier if all three share the same signature.
      
      For visitors with already track per-object state (the QMP visitors
      via a stack, and the string visitors which do not allow nesting),
      add an assertion that the caller is indeed passing the same
      pointer to paired calls.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1465490926-28625-4-git-send-email-eblake@redhat.com>
      Reviewed-by: NMarkus Armbruster <armbru@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      1158bb2a
  2. 12 5月, 2016 6 次提交
    • E
      qapi: Change visit_type_FOO() to no longer return partial objects · 68ab47e4
      Eric Blake 提交于
      Returning a partial object on error is an invitation for a careless
      caller to leak memory.  We already fixed things in an earlier
      patch to guarantee NULL if visit_start fails ("qapi: Guarantee
      NULL obj on input visitor callback error"), but that does not
      help the case where visit_start succeeds but some other failure
      happens before visit_end, such that we leak a partially constructed
      object outside visit_type_FOO(). As no one outside the testsuite
      was actually relying on these semantics, it is cleaner to just
      document and guarantee that ALL pointer-based visit_type_FOO()
      functions always leave a safe value in *obj during an input visitor
      (either the new object on success, or NULL if an error is
      encountered), so callers can now unconditionally use
      qapi_free_FOO() to clean up regardless of whether an error occurred.
      
      The decision is done by adding visit_is_input(), then updating the
      generated code to check if additional cleanup is needed based on
      the type of visitor in use.
      
      Note that we still leave *obj unchanged after a scalar-based
      visit_type_FOO(); I did not feel like auditing all uses of
      visit_type_Enum() to see if the callers would tolerate a specific
      sentinel value (not to mention having to decide whether it would
      be better to use 0 or ENUM__MAX as that sentinel).
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-25-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      68ab47e4
    • E
      qapi: Simplify semantics of visit_next_list() · d9f62dde
      Eric Blake 提交于
      The semantics of the list visit are somewhat baroque, with the
      following pseudocode when FooList is used:
      
      start()
      for (prev = head; cur = next(prev); prev = &cur) {
          visit(&cur->value)
      }
      
      Note that these semantics (advance before visit) requires that
      the first call to next() return the list head, while all other
      calls return the next element of the list; that is, every visitor
      implementation is required to track extra state to decide whether
      to return the input as-is, or to advance.  It also requires an
      argument of 'GenericList **' to next(), solely because the first
      iteration might need to modify the caller's GenericList head, so
      that all other calls have to do a layer of dereferencing.
      
      Thankfully, we only have two uses of list visits in the entire
      code base: one in spapr_drc (which completely avoids
      visit_next_list(), feeding in integers from a different source
      than uint8List), and one in qapi-visit.py.  That is, all other
      list visitors are generated in qapi-visit.c, and share the same
      paradigm based on a qapi FooList type, so we can refactor how
      lists are laid out with minimal churn among clients.
      
      We can greatly simplify things by hoisting the special case
      into the start() routine, and flipping the order in the loop
      to visit before advance:
      
      start(head)
      for (tail = *head; tail; tail = next(tail)) {
          visit(&tail->value)
      }
      
      With the simpler semantics, visitors have less state to track,
      the argument to next() is reduced to 'GenericList *', and it
      also becomes obvious whether an input visitor is allocating a
      FooList during visit_start_list() (rather than the old way of
      not knowing if an allocation happened until the first
      visit_next_list()).  As a minor drawback, we now allocate in
      two functions instead of one, and have to pass the size to
      both functions (unless we were to tweak the input visitors to
      cache the size to start_list for reuse during next_list, but
      that defeats the goal of less visitor state).
      
      The signature of visit_start_list() is chosen to match
      visit_start_struct(), with the new parameters after 'name'.
      
      The spapr_drc case is a virtual visit, done by passing NULL for
      list, similarly to how NULL is passed to visit_start_struct()
      when a qapi type is not used in those visits.  It was easy to
      provide these semantics for qmp-output and dealloc visitors,
      and a bit harder for qmp-input (several prerequisite patches
      refactored things to make this patch straightforward).  But it
      turned out that the string and opts visitors munge enough other
      state during visit_next_list() to make it easier to just
      document and require a GenericList visit for now; an assertion
      will remind us to adjust things if we need the semantics in the
      future.
      
      Several pre-requisite cleanup patches made the reshuffling of
      the various visitors easier; particularly the qmp input visitor.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-24-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      d9f62dde
    • E
      qapi: Split visit_end_struct() into pieces · 15c2f669
      Eric Blake 提交于
      As mentioned in previous patches, we want to call visit_end_struct()
      functions unconditionally, so that visitors can release resources
      tied up since the matching visit_start_struct() without also having
      to worry about error priority if more than one error occurs.
      
      Even though error_propagate() can be safely used to ignore a second
      error during cleanup caused by a first error, it is simpler if the
      cleanup cannot set an error.  So, split out the error checking
      portion (basically, input visitors checking for unvisited keys) into
      a new function visit_check_struct(), which can be safely skipped if
      any earlier errors are encountered, and leave the cleanup portion
      (which never fails, but must be called unconditionally if
      visit_start_struct() succeeded) in visit_end_struct().
      
      Generated code in qapi-visit.c has diffs resembling:
      
      |@@ -59,10 +59,12 @@ void visit_type_ACPIOSTInfo(Visitor *v,
      |         goto out_obj;
      |     }
      |     visit_type_ACPIOSTInfo_members(v, obj, &err);
      |-    error_propagate(errp, err);
      |-    err = NULL;
      |+    if (err) {
      |+        goto out_obj;
      |+    }
      |+    visit_check_struct(v, &err);
      | out_obj:
      |-    visit_end_struct(v, &err);
      |+    visit_end_struct(v);
      | out:
      
      and in qapi-event.c:
      
      @@ -47,7 +47,10 @@ void qapi_event_send_acpi_device_ost(ACP
      |         goto out;
      |     }
      |     visit_type_q_obj_ACPI_DEVICE_OST_arg_members(v, &param, &err);
      |-    visit_end_struct(v, err ? NULL : &err);
      |+    if (!err) {
      |+        visit_check_struct(v, &err);
      |+    }
      |+    visit_end_struct(v);
      |     if (err) {
      |         goto out;
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-20-git-send-email-eblake@redhat.com>
      [Conflict with a doc fixup resolved]
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      15c2f669
    • E
      qapi: Add visit_type_null() visitor · 3bc97fd5
      Eric Blake 提交于
      Right now, qmp-output-visitor happens to produce a QNull result
      if nothing is actually visited between the creation of the visitor
      and the request for the resulting QObject.  A stronger protocol
      would require that a QMP output visit MUST visit something.  But
      to still be able to produce a JSON 'null' output, we need a new
      visitor function that states our intentions.  Yes, we could say
      that such a visit must go through visit_type_any(), but that
      feels clunky.
      
      So this patch introduces the new visit_type_null() interface and
      its no-op interface in the dealloc visitor, and stubs in the
      qmp visitors (the next patch will finish the implementation).
      For the visitors that will not implement the callback, document
      the situation. The code in qapi-visit-core unconditionally
      dereferences the callback pointer, so that a segfault will inform
      a developer if they need to implement the callback for their
      choice of visitor.
      
      Note that JSON has a primitive null type, with the single value
      null; likewise with the QNull type for QObject; but for QAPI,
      we just have the 'null' value without a null type.  We may
      eventually want to add more support in QAPI for null (most likely,
      we'd use it via an alternate type that permits 'null' or an
      object); but we'll create that usage when we need it.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-15-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      3bc97fd5
    • E
      qapi: Document visitor interfaces, add assertions · adfb264c
      Eric Blake 提交于
      The visitor interface for mapping between QObject/QemuOpts/string
      and QAPI is scandalously under-documented, making changes to visitor
      core, individual visitors, and users of visitors difficult to
      coordinate.  Among other questions: when is it safe to pass NULL,
      vs. when a string must be provided; which visitors implement which
      callbacks; the difference between concrete and virtual visits.
      
      Correct this by retrofitting proper contracts, and document where some
      of the interface warts remain (for example, we may want to modify
      visit_end_* to require the same 'obj' as the visit_start counterpart,
      so the dealloc visitor can be simplified).  Later patches in this
      series will tackle some, but not all, of these warts.
      
      Add assertions to (partially) enforce the contract.  Some of these
      were only made possible by recent cleanup commits.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-13-git-send-email-eblake@redhat.com>
      [Doc fix from Eric squashed in]
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      adfb264c
    • E
      qapi-visit: Add visitor.type classification · 983f52d4
      Eric Blake 提交于
      We have three classes of QAPI visitors: input, output, and dealloc.
      Currently, all implementations of these visitors have one thing in
      common based on their visitor type: the implementation used for the
      visit_type_enum() callback.  But since we plan to add more such
      common behavior, in relation to documenting and further refining
      the semantics, it makes more sense to have the visitor
      implementations advertise which class they belong to, so the common
      qapi-visit-core code can use that information in multiple places.
      
      A later patch will better document the types of visitors directly
      in visitor.h.
      
      For this patch, knowing the class of a visitor implementation lets
      us make input_type_enum() and output_type_enum() become static
      functions, by replacing the callback function Visitor.type_enum()
      with the simpler enum member Visitor.type.  Share a common
      assertion in qapi-visit-core as part of the refactoring.
      
      Move comments in opts-visitor.c to match the refactored layout.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1461879932-9020-2-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      983f52d4
  3. 23 3月, 2016 1 次提交
  4. 23 2月, 2016 1 次提交
    • P
      include: Clean up includes · 90ce6e26
      Peter Maydell 提交于
      Clean up includes so that osdep.h is included first and headers
      which it implies are not included manually.
      
      This commit was created with scripts/clean-includes.
      
      NB: If this commit breaks compilation for your out-of-tree
      patchseries or fork, then you need to make sure you add
      #include "qemu/osdep.h" to any new .c files that you have.
      Signed-off-by: NPeter Maydell <peter.maydell@linaro.org>
      Reviewed-by: NEric Blake <eblake@redhat.com>
      90ce6e26
  5. 19 2月, 2016 3 次提交
    • E
      qapi: Change visit_start_implicit_struct to visit_start_alternate · dbf11922
      Eric Blake 提交于
      After recent changes, the only remaining use of
      visit_start_implicit_struct() is for allocating the space needed
      when visiting an alternate.  Since the term 'implicit struct' is
      hard to explain, rename the function to its current usage.  While
      at it, we can merge the functionality of visit_get_next_type()
      into the same function, making it more like visit_start_struct().
      
      Generated code is now slightly smaller:
      
      | {
      |     Error *err = NULL;
      |
      |-    visit_start_implicit_struct(v, (void**) obj, sizeof(BlockdevRef), &err);
      |+    visit_start_alternate(v, name, (GenericAlternate **)obj, sizeof(**obj),
      |+                          true, &err);
      |     if (err) {
      |         goto out;
      |     }
      |-    visit_get_next_type(v, name, &(*obj)->type, true, &err);
      |-    if (err) {
      |-        goto out_obj;
      |-    }
      |     switch ((*obj)->type) {
      |     case QTYPE_QDICT:
      |         visit_start_struct(v, name, NULL, 0, &err);
      ...
      |     }
      |-out_obj:
      |-    visit_end_implicit_struct(v);
      |+    visit_end_alternate(v);
      | out:
      |     error_propagate(errp, err);
      | }
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1455778109-6278-16-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      dbf11922
    • E
      qapi: Don't box branches of flat unions · 544a3731
      Eric Blake 提交于
      There's no reason to do two malloc's for a flat union; let's just
      inline the branch struct directly into the C union branch of the
      flat union.
      
      Surprisingly, fewer clients were actually using explicit references
      to the branch types in comparison to the number of flat unions
      thus modified.
      
      This lets us reduce the hack in qapi-types:gen_variants() added in
      the previous patch; we no longer need to distinguish between
      alternates and flat unions.
      
      The change to unboxed structs means that u.data (added in commit
      cee2dedb) is now coincident with random fields of each branch of
      the flat union, whereas beforehand it was only coincident with
      pointers (since all branches of a flat union have to be objects).
      Note that this was already the case for simple unions - but there
      we got lucky.  Remember, visit_start_union() blindly returns true
      for all visitors except for the dealloc visitor, where it returns
      the value !!obj->u.data, and that this result then controls
      whether to proceed with the visit to the variant.  Pre-patch,
      this meant that flat unions were testing whether the boxed pointer
      was still NULL, and thereby skipping visit_end_implicit_struct()
      and avoiding a NULL dereference if the pointer had not been
      allocated.  The same was true for simple unions where the current
      branch had pointer type, except there we bypassed visit_type_FOO().
      But for simple unions where the current branch had scalar type, the
      contents of that scalar meant that the decision to call
      visit_type_FOO() was data-dependent - the reason we got lucky there
      is that visit_type_FOO() for all scalar types in the dealloc visitor
      is a no-op (only the pointer variants had anything to free), so it
      did not matter whether the dealloc visit was skipped.  But with this
      patch, we would risk leaking memory if we could skip a call to
      visit_type_FOO_fields() based solely on a data-dependent decision.
      
      But notice: in the dealloc visitor, visit_type_FOO() already handles
      a NULL obj - it was only the visit_type_implicit_FOO() that was
      failing to check for NULL. And now that we have refactored things to
      have the branch be part of the parent struct, we no longer have a
      separate pointer that can be NULL in the first place.  So we can just
      delete the call to visit_start_union() altogether, and blindly visit
      the branch type; there is no change in behavior except to the dealloc
      visitor, where we now unconditionally visit the branch, but where that
      visit is now always safe (for a flat union, we can no longer
      dereference NULL, and for a simple union, visit_type_FOO() was already
      safely handling NULL on pointer types).
      
      Unfortunately, simple unions are not as easy to switch to unboxed
      layout; because we are special-casing the hidden implicit type with
      a single 'data' member, we really DO need to keep calling another
      layer of visit_start_struct(), with a second malloc; although there
      are some cleanups planned for simple unions in later patches.
      
      visit_start_union() and gen_visit_implicit_struct() are now unused.
      Drop them.
      
      Note that after this patch, the only remaining use of
      visit_start_implicit_struct() is for alternate types; the next patch
      will do further cleanup based on that fact.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1455778109-6278-14-git-send-email-eblake@redhat.com>
      [Dead code deletion squashed in, commit message updated accordingly]
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      544a3731
    • E
      qapi: Adjust layout of FooList types · e65d89bf
      Eric Blake 提交于
      By sticking the next pointer first, we don't need a union with
      64-bit padding for smaller types.  On 32-bit platforms, this
      can reduce the size of uint8List from 16 bytes (or 12, depending
      on whether 64-bit ints can tolerate 4-byte alignment) down to 8.
      It has no effect on 64-bit platforms (where alignment still
      dictates a 16-byte struct); but fewer anonymous unions is still
      a win in my book.
      
      It requires visit_next_list() to gain a size parameter, to know
      what size element to allocate; comparable to the size parameter
      of visit_start_struct().
      
      I debated about going one step further, to allow for fewer casts,
      by doing:
          typedef GenericList GenericList;
          struct GenericList {
              GenericList *next;
          };
          struct FooList {
              GenericList base;
              Foo *value;
          };
      so that you convert to 'GenericList *' by '&foolist->base', and
      back by 'container_of(generic, GenericList, base)' (as opposed to
      the existing '(GenericList *)foolist' and '(FooList *)generic').
      But doing that would require hoisting the declaration of
      GenericList prior to inclusion of qapi-types.h, rather than its
      current spot in visitor.h; it also makes iteration a bit more
      verbose through 'foolist->base.next' instead of 'foolist->next'.
      
      Note that for lists of objects, the 'value' payload is still
      hidden behind a boxed pointer.  Someday, it would be nice to do:
      
      struct FooList {
          FooList *next;
          Foo value;
      };
      
      for one less level of malloc for each list element.  This patch
      is a step in that direction (now that 'next' is no longer at a
      fixed non-zero offset within the struct, we can store more than
      just a pointer's-worth of data as the value payload), but the
      actual conversion would be a task for another series, as it will
      touch a lot of code.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1455778109-6278-10-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      e65d89bf
  6. 09 2月, 2016 4 次提交
    • E
      qapi: Drop unused error argument for list and implicit struct · 08f9541d
      Eric Blake 提交于
      No backend was setting an error when ending the visit of a list or
      implicit struct, or when moving to the next list node.  Make the
      callers a bit easier to follow by making this a part of the contract,
      and removing the errp argument - callers can then unconditionally end
      an object as part of cleanup without having to think about whether a
      second error is dominated by a first, because there is no second
      error.
      
      A later patch will then tackle the larger task of splitting
      visit_end_struct(), which can indeed set an error.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1454075341-13658-24-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      08f9541d
    • E
      qapi: Drop unused 'kind' for struct/enum visit · 337283df
      Eric Blake 提交于
      visit_start_struct() and visit_type_enum() had a 'kind' argument
      that was usually set to either the stringized version of the
      corresponding qapi type name, or to NULL (although some clients
      didn't even get that right).  But nothing ever used the argument.
      It's even hard to argue that it would be useful in a debugger,
      as a stack backtrace also tells which type is being visited.
      
      Therefore, drop the 'kind' argument as dead.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Reviewed-by: NMarc-André Lureau <marcandre.lureau@redhat.com>
      Message-Id: <1454075341-13658-22-git-send-email-eblake@redhat.com>
      [Harmless rebase mistake cleaned up]
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      337283df
    • E
      qapi: Swap visit_* arguments for consistent 'name' placement · 51e72bc1
      Eric Blake 提交于
      JSON uses "name":value, but many of our visitor interfaces were
      called with visit_type_FOO(v, &value, name, errp).  This can be
      a bit confusing to have to mentally swap the parameter order to
      match JSON order.  It's particularly bad for visit_start_struct(),
      where the 'name' parameter is smack in the middle of the
      otherwise-related group of 'obj, kind, size' parameters! It's
      time to do a global swap of the parameter ordering, so that the
      'name' parameter is always immediately after the Visitor argument.
      
      Additional reason in favor of the swap: the existing include/qjson.h
      prefers listing 'name' first in json_prop_*(), and I have plans to
      unify that file with the qapi visitors; listing 'name' first in
      qapi will minimize churn to the (admittedly few) qjson.h clients.
      
      Later patches will then fix docs, object.h, visitor-impl.h, and
      those clients to match.
      
      Done by first patching scripts/qapi*.py by hand to make generated
      files do what I want, then by running the following Coccinelle
      script to affect the rest of the code base:
       $ spatch --sp-file script `git grep -l '\bvisit_' -- '**/*.[ch]'`
      I then had to apply some touchups (Coccinelle insisted on TAB
      indentation in visitor.h, and botched the signature of
      visit_type_enum() by rewriting 'const char *const strings[]' to
      the syntactically invalid 'const char*const[] strings').  The
      movement of parameters is sufficient to provoke compiler errors
      if any callers were missed.
      
          // Part 1: Swap declaration order
          @@
          type TV, TErr, TObj, T1, T2;
          identifier OBJ, ARG1, ARG2;
          @@
           void visit_start_struct
          -(TV v, TObj OBJ, T1 ARG1, const char *name, T2 ARG2, TErr errp)
          +(TV v, const char *name, TObj OBJ, T1 ARG1, T2 ARG2, TErr errp)
           { ... }
      
          @@
          type bool, TV, T1;
          identifier ARG1;
          @@
           bool visit_optional
          -(TV v, T1 ARG1, const char *name)
          +(TV v, const char *name, T1 ARG1)
           { ... }
      
          @@
          type TV, TErr, TObj, T1;
          identifier OBJ, ARG1;
          @@
           void visit_get_next_type
          -(TV v, TObj OBJ, T1 ARG1, const char *name, TErr errp)
          +(TV v, const char *name, TObj OBJ, T1 ARG1, TErr errp)
           { ... }
      
          @@
          type TV, TErr, TObj, T1, T2;
          identifier OBJ, ARG1, ARG2;
          @@
           void visit_type_enum
          -(TV v, TObj OBJ, T1 ARG1, T2 ARG2, const char *name, TErr errp)
          +(TV v, const char *name, TObj OBJ, T1 ARG1, T2 ARG2, TErr errp)
           { ... }
      
          @@
          type TV, TErr, TObj;
          identifier OBJ;
          identifier VISIT_TYPE =~ "^visit_type_";
          @@
           void VISIT_TYPE
          -(TV v, TObj OBJ, const char *name, TErr errp)
          +(TV v, const char *name, TObj OBJ, TErr errp)
           { ... }
      
          // Part 2: swap caller order
          @@
          expression V, NAME, OBJ, ARG1, ARG2, ERR;
          identifier VISIT_TYPE =~ "^visit_type_";
          @@
          (
          -visit_start_struct(V, OBJ, ARG1, NAME, ARG2, ERR)
          +visit_start_struct(V, NAME, OBJ, ARG1, ARG2, ERR)
          |
          -visit_optional(V, ARG1, NAME)
          +visit_optional(V, NAME, ARG1)
          |
          -visit_get_next_type(V, OBJ, ARG1, NAME, ERR)
          +visit_get_next_type(V, NAME, OBJ, ARG1, ERR)
          |
          -visit_type_enum(V, OBJ, ARG1, ARG2, NAME, ERR)
          +visit_type_enum(V, NAME, OBJ, ARG1, ARG2, ERR)
          |
          -VISIT_TYPE(V, OBJ, NAME, ERR)
          +VISIT_TYPE(V, NAME, OBJ, ERR)
          )
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Reviewed-by: NMarc-André Lureau <marcandre.lureau@redhat.com>
      Message-Id: <1454075341-13658-19-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      51e72bc1
    • E
      qapi-visit: Kill unused visit_end_union() · 7c91aabd
      Eric Blake 提交于
      The generated code can call visit_end_union() without having called
      visit_start_union().  Example:
      
              if (!*obj) {
                  goto out_obj;
              }
              visit_type_CpuInfoBase_fields(v, (CpuInfoBase **)obj, &err);
              if (err) {
                  goto out_obj; // if we go from here...
              }
              if (!visit_start_union(v, !!(*obj)->u.data, &err) || err) {
                  goto out_obj;
              }
              switch ((*obj)->arch) {
          [...]
              }
          out_obj:
              // ... then *obj is true, and ...
              error_propagate(errp, err);
              err = NULL;
              if (*obj) {
                  // we end up here
                  visit_end_union(v, !!(*obj)->u.data, &err);
              }
              error_propagate(errp, err);
      
      Harmless only because no visitor implements end_union().  Clean it up
      anyway, by deleting the function as useless.
      
      Messed up since we have visit_end_union (commit cee2dedb).
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      Message-Id: <1453902888-20457-3-git-send-email-armbru@redhat.com>
      [expand scope of patch to delete rather than repair]
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1454075341-13658-13-git-send-email-eblake@redhat.com>
      7c91aabd
  7. 17 12月, 2015 5 次提交
    • E
      qapi: Shorter visits of optional fields · 29637a6e
      Eric Blake 提交于
      For less code, reflect the determined boolean value of an optional
      visit back to the caller instead of making the caller read the
      boolean after the fact.
      
      The resulting generated code has the following diff:
      
      |-    visit_optional(v, &has_fdset_id, "fdset-id");
      |-    if (has_fdset_id) {
      |+    if (visit_optional(v, &has_fdset_id, "fdset-id")) {
      |         visit_type_int(v, &fdset_id, "fdset-id", &err);
      |         if (err) {
      |             goto out;
      |         }
      |     }
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1449033659-25497-10-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      29637a6e
    • E
      qapi: Simplify visits of optional fields · 5cdc8831
      Eric Blake 提交于
      None of the visitor callbacks would set an error when testing
      if an optional field was present; make this part of the interface
      contract by eliminating the errp argument.
      
      The resulting generated code has a nice diff:
      
      |-    visit_optional(v, &has_fdset_id, "fdset-id", &err);
      |-    if (err) {
      |-        goto out;
      |-    }
      |+    visit_optional(v, &has_fdset_id, "fdset-id");
      |     if (has_fdset_id) {
      |         visit_type_int(v, &fdset_id, "fdset-id", &err);
      |         if (err) {
      |             goto out;
      |         }
      |     }
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1449033659-25497-9-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      5cdc8831
    • E
      qapi: Fix alternates that accept 'number' but not 'int' · d00341af
      Eric Blake 提交于
      The QMP input visitor allows integral values to be assigned by
      promotion to a QTYPE_QFLOAT.  However, when parsing an alternate,
      we did not take this into account, such that an alternate that
      accepts 'number' and some other type, but not 'int', would reject
      integral values.
      
      With this patch, we now have the following desirable table:
      
          alternate has      case selected for
          'int'  'number'    QTYPE_QINT  QTYPE_QFLOAT
            no        no     error       error
            no       yes     'number'    'number'
           yes        no     'int'       error
           yes       yes     'int'       'number'
      
      While it is unlikely that we will ever use 'number' in an
      alternate other than in the testsuite, it never hurts to be
      more precise in what we allow.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1449033659-25497-8-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      d00341af
    • E
      qapi: Simplify visiting of alternate types · 0426d53c
      Eric Blake 提交于
      Previously, working with alternates required two lookup arrays
      and some indirection: for type Foo, we created Foo_qtypes[]
      which maps each qtype to a value of the generated FooKind enum,
      then look up that value in FooKind_lookup[] like we do for other
      union types.
      
      This has a couple of subtle bugs.  First, the generator was
      creating a call with a parameter '(int *) &(*obj)->type' where
      type is an enum type; this is unsafe if the compiler chooses
      to store the enum type in a different size than int, where
      assigning through the wrong size pointer can corrupt data or
      cause a SIGBUS.
      
      Related bug, not not fixed in this patch: qapi-visit.py's
      gen_visit_enum() generates a cast of its enum * argument to
      int *. Marked FIXME.
      
      Second, since the values of the FooKind enum start at zero, all
      entries of the Foo_qtypes[] array that were not explicitly
      initialized will map to the same branch of the union as the
      first member of the alternate, rather than triggering a desired
      failure in visit_get_next_type().  Fortunately, the bug seldom
      bites; the very next thing the input visitor does is try to
      parse the incoming JSON with the wrong parser, which normally
      fails; the output visitor is not used with a C struct in that
      state, and the dealloc visitor has nothing to clean up (so
      there is no leak).
      
      However, the second bug IS observable in one case: parsing an
      integer causes unusual behavior in an alternate that contains
      at least a 'number' member but no 'int' member, because the
      'number' parser accepts QTYPE_QINT in addition to the expected
      QTYPE_QFLOAT (that is, since 'int' is not a member, the type
      QTYPE_QINT accidentally maps to FooKind 0; if this enum value
      is the 'number' branch the integer parses successfully, but if
      the 'number' branch is not first, some other branch tries to
      parse the integer and rejects it).  A later patch will worry
      about fixing alternates to always parse all inputs that a
      non-alternate 'number' would accept, for now this is still
      marked FIXME in the updated test-qmp-input-visitor.c, to
      merely point out that new undesired behavior of 'ans' matches
      the existing undesired behavior of 'asn'.
      
      This patch fixes the default-initialization bug by deleting the
      indirection, and modifying get_next_type() to directly assign a
      QTypeCode parameter.  This in turn fixes the type-casting bug,
      as we are no longer casting a pointer to enum to a questionable
      size. There is no longer a need to generate an implicit FooKind
      enum associated with the alternate type (since the QMP wire
      format never uses the stringized counterparts of the C union
      member names).  Since the updated visit_get_next_type() does not
      know which qtypes are expected, the generated visitor is
      modified to generate an error statement if an unexpected type is
      encountered.
      
      Callers now have to know the QTYPE_* mapping when looking at the
      discriminator; but so far, only the testsuite was even using the
      C struct of an alternate types.  I considered the possibility of
      keeping the internal enum FooKind, but initialized differently
      than most generated arrays, as in:
        typedef enum FooKind {
            FOO_KIND_A = QTYPE_QDICT,
            FOO_KIND_B = QTYPE_QINT,
        } FooKind;
      to create nicer aliases for knowing when to use foo->a or foo->b
      when inspecting foo->type; but it turned out to add too much
      complexity, especially without a client.
      
      There is a user-visible side effect to this change, but I
      consider it to be an improvement. Previously,
      the invalid QMP command:
        {"execute":"blockdev-add", "arguments":{"options":
          {"driver":"raw", "id":"a", "file":true}}}
      failed with:
        {"error": {"class": "GenericError",
          "desc": "Invalid parameter type for 'file', expected: QDict"}}
      (visit_get_next_type() succeeded, and the error comes from the
      visit_type_BlockdevOptions() expecting {}; there is no mention of
      the fact that a string would also work).  Now it fails with:
        {"error": {"class": "GenericError",
          "desc": "Invalid parameter type for 'file', expected: BlockdevRef"}}
      (the error when the next type doesn't match any expected types for
      the overall alternate).
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1449033659-25497-5-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      0426d53c
    • E
      qapi: Remove dead visitor code · 75494572
      Eric Blake 提交于
      Commit cbc95538 removed unused start_handle() and end_handle(),
      but forgot to remove their declarations.
      Signed-off-by: NEric Blake <eblake@redhat.com>
      Message-Id: <1447836791-369-19-git-send-email-eblake@redhat.com>
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      75494572
  8. 21 9月, 2015 1 次提交
  9. 20 6月, 2015 1 次提交
  10. 27 9月, 2014 1 次提交
    • M
      qapi: add visit_start_union and visit_end_union · cee2dedb
      Michael Roth 提交于
      In some cases an input visitor might bail out on filling out a
      struct for various reasons, such as missing fields when running
      in strict mode. In the case of a QAPI Union type, this may lead
      to cases where the .kind field which encodes the union type
      is uninitialized. Subsequently, other visitors, such as the
      dealloc visitor, may use this .kind value as if it were
      initialized, leading to assumptions about the union type which
      in this case may lead to segfaults. For example, freeing an
      integer value.
      
      However, we can generally rely on the fact that the always-present
      .data void * field that we generate for these union types will
      always be NULL in cases where .kind is uninitialized (at least,
      there shouldn't be a reason where we'd do this purposefully).
      
      So pass this information on to Visitor implementation via these
      optional start_union/end_union interfaces so this information
      can be used to guard against the situation above. We will make
      use of this information in a subsequent patch for the dealloc
      visitor.
      
      Cc: qemu-stable@nongnu.org
      Reported-by: NFam Zheng <famz@redhat.com>
      Suggested-by: NPaolo Bonzini <pbonzini@redhat.com>
      Reviewed-by: NPaolo Bonzini <pbonzini@redhat.com>
      Reviewed-by: NEric Blake <eblake@redhat.com>
      Signed-off-by: NMichael Roth <mdroth@linux.vnet.ibm.com>
      Signed-off-by: NLuiz Capitulino <lcapitulino@redhat.com>
      cee2dedb
  11. 16 5月, 2014 1 次提交
    • M
      qapi: Replace start_optional()/end_optional() by optional() · e2cd0f4f
      Markus Armbruster 提交于
      Semantics of end_optional() differ subtly from the other end_FOO()
      callbacks: when start_FOO() succeeds, the matching end_FOO() gets
      called regardless of what happens in between.  end_optional() gets
      called only when everything in between succeeds as well.  Entirely
      undocumented, like all of the visitor API.
      
      The only user of Visitor Callback end_optional() never did anything,
      and was removed in commit 9f9ab465.
      
      I'm about to clean up error handling in the generated visitor code,
      and end_optional() is in my way.  No users mean no test cases, and
      making non-trivial cleanup transformations without test cases doesn't
      strike me as a good idea.
      
      Drop end_optional(), and rename start_optional() to optional().  We
      can always go back to a pair of callbacks when we have an actual need.
      Signed-off-by: NMarkus Armbruster <armbru@redhat.com>
      Reviewed-by: NEric Blake <eblake@redhat.com>
      Signed-off-by: NLuiz Capitulino <lcapitulino@redhat.com>
      e2cd0f4f
  12. 07 1月, 2014 1 次提交
  13. 27 7月, 2013 2 次提交
    • K
      qapi: Anonymous unions · 69dd62df
      Kevin Wolf 提交于
      The discriminator for anonymous unions is the data type. This allows to
      have a union type that allows both of these:
      
          { 'file': 'my_existing_block_device_id' }
          { 'file': { 'filename': '/tmp/mydisk.qcow2', 'read-only': true } }
      
      Unions like this are specified in the schema with an empty dict as
      discriminator. For this example you could take:
      
          { 'union': 'BlockRef',
            'discriminator': {},
            'data': { 'definition': 'BlockOptions',
                      'reference': 'str' } }
          { 'type': 'ExampleObject',
            'data: { 'file': 'BlockRef' } }
      Signed-off-by: NKevin Wolf <kwolf@redhat.com>
      Reviewed-by: NEric Blake <eblake@redhat.com>
      69dd62df
    • K
      qapi: Add visitor for implicit structs · 761d524d
      Kevin Wolf 提交于
      These can be used when an embedded struct is parsed and members not
      belonging to the struct may be present in the input (e.g. parsing a
      flat namespace QMP union, where fields from both the base and one
      of the alternative types are mixed in the JSON object)
      Signed-off-by: NKevin Wolf <kwolf@redhat.com>
      Reviewed-by: NEric Blake <eblake@redhat.com>
      761d524d
  14. 30 5月, 2013 1 次提交
    • M
      qapi: pad GenericList value fields to 64 bits · a678e26c
      Michael Roth 提交于
      With the introduction of native list types, we now have types such as
      int64List where the 'value' field is not a pointer, but the actual
      64-bit value.
      
      On 32-bit architectures, this can lead to situations where 'next' field
      offset in GenericList does not correspond to the 'next' field in the
      types that we cast to GenericList when using the visit_next_list()
      interface, causing issues when we attempt to traverse linked list
      structures of these types.
      
      To fix this, pad the 'value' field of GenericList and other
      schema-defined/native *List types out to 64-bits.
      
      This is less memory-efficient for 32-bit architectures, but allows us to
      continue to rely on list-handling interfaces that target GenericList to
      simply visitor implementations.
      
      In the future we can improve efficiency by defaulting to using native C
      array backends to handle list of non-pointer types, which would be more
      memory efficient in itself and allow us to roll back this change.
      Signed-off-by: NMichael Roth <mdroth@linux.vnet.ibm.com>
      Signed-off-by: NLuiz Capitulino <lcapitulino@redhat.com>
      a678e26c
  15. 19 12月, 2012 3 次提交
  16. 23 7月, 2012 1 次提交
  17. 08 6月, 2012 1 次提交
  18. 22 7月, 2011 1 次提交
    • M
      qapi: add QAPI visitor core · 2345c77c
      Michael Roth 提交于
      Base definitions/includes for Visiter interface used by generated
      visiter/marshalling code.
      
      Includes a GenericList type. Our lists require an embedded element.
      Since these types are generated, if you want to use them in a different
      type of data structure, there's no easy way to add another embedded
      element. The solution is to have non-embedded lists and that what this is.
      Signed-off-by: NMichael Roth <mdroth@linux.vnet.ibm.com>
      Signed-off-by: NLuiz Capitulino <lcapitulino@gmail.com>
      2345c77c