Add an accessor for the loader's corruption reason
[platform/upstream/dbus.git] / dbus / dbus-message.c
index 4ddfa37..272592e 100644 (file)
@@ -1,4 +1,4 @@
-/* -*- mode: C; c-file-style: "gnu" -*- */
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
 /* dbus-message.c  DBusMessage object
  *
  * Copyright (C) 2002, 2003, 2004, 2005  Red Hat Inc.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  *
  */
 
 #include "dbus-internals.h"
 #include "dbus-marshal-recursive.h"
 #include "dbus-marshal-validate.h"
+#include "dbus-marshal-byteswap.h"
 #include "dbus-marshal-header.h"
+#include "dbus-signature.h"
 #include "dbus-message-private.h"
 #include "dbus-object-tree.h"
 #include "dbus-memory.h"
 #include "dbus-list.h"
+#include "dbus-threads-internal.h"
 #include <string.h>
 
+static void dbus_message_finalize (DBusMessage *message);
+
 /**
  * @defgroup DBusMessageInternals DBusMessage implementation details
  * @ingroup DBusInternals
@@ -76,11 +81,68 @@ struct DBusMessageRealIter
   } u; /**< the type writer or reader that does all the work */
 };
 
+static void
+get_const_signature (DBusHeader        *header,
+                     const DBusString **type_str_p,
+                     int               *type_pos_p)
+{
+  if (_dbus_header_get_field_raw (header,
+                                  DBUS_HEADER_FIELD_SIGNATURE,
+                                  type_str_p,
+                                  type_pos_p))
+    {
+      *type_pos_p += 1; /* skip the signature length which is 1 byte */
+    }
+  else
+    {
+      *type_str_p = &_dbus_empty_signature_str;
+      *type_pos_p = 0;
+    }
+}
+
+/**
+ * Swaps the message to compiler byte order if required
+ *
+ * @param message the message
+ */
+static void
+_dbus_message_byteswap (DBusMessage *message)
+{
+  const DBusString *type_str;
+  int type_pos;
+  
+  if (message->byte_order == DBUS_COMPILER_BYTE_ORDER)
+    return;
+
+  _dbus_verbose ("Swapping message into compiler byte order\n");
+  
+  get_const_signature (&message->header, &type_str, &type_pos);
+  
+  _dbus_marshal_byteswap (type_str, type_pos,
+                          message->byte_order,
+                          DBUS_COMPILER_BYTE_ORDER,
+                          &message->body, 0);
+
+  message->byte_order = DBUS_COMPILER_BYTE_ORDER;
+  
+  _dbus_header_byteswap (&message->header, DBUS_COMPILER_BYTE_ORDER);
+}
+
+/** byte-swap the message if it doesn't match our byte order.
+ *  Called only when we need the message in our own byte order,
+ *  normally when reading arrays of integers or doubles.
+ *  Otherwise should not be called since it would do needless
+ *  work.
+ */
+#define ensure_byte_order(message)                      \
+ if (message->byte_order != DBUS_COMPILER_BYTE_ORDER)   \
+   _dbus_message_byteswap (message)
+
 /**
  * Gets the data to be sent over the network for this message.
  * The header and then the body should be written out.
  * This function is guaranteed to always return the same
- * data once a message is locked (with _dbus_message_lock()).
+ * data once a message is locked (with dbus_message_lock()).
  *
  * @param message the message.
  * @param header return location for message header data.
@@ -101,16 +163,19 @@ _dbus_message_get_network_data (DBusMessage          *message,
  * Sets the serial number of a message.
  * This can only be done once on a message.
  *
+ * DBusConnection will automatically set the serial to an appropriate value 
+ * when the message is sent; this function is only needed when encapsulating 
+ * messages in another protocol, or otherwise bypassing DBusConnection.
+ *
  * @param message the message
  * @param serial the serial
  */
-void
-_dbus_message_set_serial (DBusMessage   *message,
-                          dbus_uint32_t  serial)
+void 
+dbus_message_set_serial (DBusMessage   *message,
+                         dbus_uint32_t  serial)
 {
-  _dbus_assert (message != NULL);
-  _dbus_assert (!message->locked);
-  _dbus_assert (dbus_message_get_serial (message) == 0);
+  _dbus_return_if_fail (message != NULL);
+  _dbus_return_if_fail (!message->locked);
 
   _dbus_header_set_serial (&message->header, serial);
 }
@@ -215,12 +280,13 @@ _dbus_message_remove_size_counter (DBusMessage  *message,
  * reference to a message in the outgoing queue and change it
  * underneath us. Messages are locked when they enter the outgoing
  * queue (dbus_connection_send_message()), and the library complains
- * if the message is modified while locked.
+ * if the message is modified while locked. This function may also 
+ * called externally, for applications wrapping D-Bus in another protocol.
  *
  * @param message the message to lock.
  */
 void
-_dbus_message_lock (DBusMessage  *message)
+dbus_message_lock (DBusMessage  *message)
 {
   if (!message->locked)
     {
@@ -250,25 +316,6 @@ set_or_delete_string_field (DBusMessage *message,
                                          &value);
 }
 
-static void
-get_const_signature (DBusHeader        *header,
-                     const DBusString **type_str_p,
-                     int               *type_pos_p)
-{
-  if (_dbus_header_get_field_raw (header,
-                                  DBUS_HEADER_FIELD_SIGNATURE,
-                                  type_str_p,
-                                  type_pos_p))
-    {
-      *type_pos_p += 1; /* skip the signature length which is 1 byte */
-    }
-  else
-    {
-      *type_str_p = &_dbus_empty_signature_str;
-      *type_pos_p = 0;
-    }
-}
-
 #if 0
 /* Probably we don't need to use this */
 /**
@@ -313,119 +360,6 @@ _dbus_message_set_signature (DBusMessage *message,
 }
 #endif
 
-/** @} */
-
-/**
- * @defgroup DBusMessage DBusMessage
- * @ingroup  DBus
- * @brief Message to be sent or received over a DBusConnection.
- *
- * A DBusMessage is the most basic unit of communication over a
- * DBusConnection. A DBusConnection represents a stream of messages
- * received from a remote application, and a stream of messages
- * sent to a remote application.
- *
- * @{
- */
-
-/**
- * @typedef DBusMessage
- *
- * Opaque data type representing a message received from or to be
- * sent to another application.
- */
-
-/**
- * Returns the serial of a message or 0 if none has been specified.
- * The message's serial number is provided by the application sending
- * the message and is used to identify replies to this message.  All
- * messages received on a connection will have a serial, but messages
- * you haven't sent yet may return 0.
- *
- * @param message the message
- * @returns the client serial
- */
-dbus_uint32_t
-dbus_message_get_serial (DBusMessage *message)
-{
-  _dbus_return_val_if_fail (message != NULL, 0);
-
-  return _dbus_header_get_serial (&message->header);
-}
-
-/**
- * Sets the reply serial of a message (the client serial
- * of the message this is a reply to).
- *
- * @param message the message
- * @param reply_serial the client serial
- * @returns #FALSE if not enough memory
- */
-dbus_bool_t
-dbus_message_set_reply_serial (DBusMessage   *message,
-                               dbus_uint32_t  reply_serial)
-{
-  _dbus_return_val_if_fail (message != NULL, FALSE);
-  _dbus_return_val_if_fail (!message->locked, FALSE);
-
-  return _dbus_header_set_field_basic (&message->header,
-                                       DBUS_HEADER_FIELD_REPLY_SERIAL,
-                                       DBUS_TYPE_UINT32,
-                                       &reply_serial);
-}
-
-/**
- * Returns the serial that the message is a reply to or 0 if none.
- *
- * @param message the message
- * @returns the reply serial
- */
-dbus_uint32_t
-dbus_message_get_reply_serial  (DBusMessage *message)
-{
-  dbus_uint32_t v_UINT32;
-
-  _dbus_return_val_if_fail (message != NULL, 0);
-
-  if (_dbus_header_get_field_basic (&message->header,
-                                    DBUS_HEADER_FIELD_REPLY_SERIAL,
-                                    DBUS_TYPE_UINT32,
-                                    &v_UINT32))
-    return v_UINT32;
-  else
-    return 0;
-}
-
-static void
-free_size_counter (void *element,
-                   void *data)
-{
-  DBusCounter *counter = element;
-  DBusMessage *message = data;
-
-  _dbus_counter_adjust (counter, - message->size_counter_delta);
-
-  _dbus_counter_unref (counter);
-}
-
-static void
-dbus_message_finalize (DBusMessage *message)
-{
-  _dbus_assert (message->refcount.value == 0);
-
-  /* This calls application callbacks! */
-  _dbus_data_slot_list_free (&message->slot_list);
-
-  _dbus_list_foreach (&message->size_counters,
-                      free_size_counter, message);
-  _dbus_list_clear (&message->size_counters);
-
-  _dbus_header_free (&message->header);
-  _dbus_string_free (&message->body);
-
-  dbus_free (message);
-}
-
 /* Message Cache
  *
  * We cache some DBusMessage to reduce the overhead of allocating
@@ -473,7 +407,7 @@ dbus_message_finalize (DBusMessage *message)
  */
 
 /** Avoid caching huge messages */
-#define MAX_MESSAGE_SIZE_TO_CACHE _DBUS_ONE_MEGABYTE
+#define MAX_MESSAGE_SIZE_TO_CACHE 10 * _DBUS_ONE_KILOBYTE
 
 /** Avoid caching too many messages */
 #define MAX_MESSAGE_CACHE_SIZE    5
@@ -552,14 +486,26 @@ dbus_message_get_cached (void)
   _dbus_assert (i < MAX_MESSAGE_CACHE_SIZE);
   _dbus_assert (message != NULL);
 
-  _DBUS_UNLOCK (message_cache);
-
   _dbus_assert (message->refcount.value == 0);
   _dbus_assert (message->size_counters == NULL);
+  
+  _DBUS_UNLOCK (message_cache);
 
   return message;
 }
 
+static void
+free_size_counter (void *element,
+                   void *data)
+{
+  DBusCounter *counter = element;
+  DBusMessage *message = data;
+
+  _dbus_counter_adjust (counter, - message->size_counter_delta);
+
+  _dbus_counter_unref (counter);
+}
+
 /**
  * Tries to cache a message, otherwise finalize it.
  *
@@ -570,7 +516,7 @@ dbus_message_cache_or_finalize (DBusMessage *message)
 {
   dbus_bool_t was_cached;
   int i;
-
+  
   _dbus_assert (message->refcount.value == 0);
 
   /* This calls application code and has to be done first thing
@@ -624,78 +570,455 @@ dbus_message_cache_or_finalize (DBusMessage *message)
   message_cache[i] = message;
   message_cache_count += 1;
   was_cached = TRUE;
+#ifndef DBUS_DISABLE_CHECKS
+  message->in_cache = TRUE;
+#endif
 
  out:
+  _dbus_assert (message->refcount.value == 0);
+  
   _DBUS_UNLOCK (message_cache);
-
+  
   if (!was_cached)
     dbus_message_finalize (message);
 }
 
-static DBusMessage*
-dbus_message_new_empty_header (void)
+#ifndef DBUS_DISABLE_CHECKS
+static dbus_bool_t
+_dbus_message_iter_check (DBusMessageRealIter *iter)
 {
-  DBusMessage *message;
-  dbus_bool_t from_cache;
-
-  message = dbus_message_get_cached ();
-
-  if (message != NULL)
-    {
-      from_cache = TRUE;
-    }
-  else
+  if (iter == NULL)
     {
-      from_cache = FALSE;
-      message = dbus_new (DBusMessage, 1);
-      if (message == NULL)
-        return NULL;
-#ifndef DBUS_DISABLE_CHECKS
-      message->generation = _dbus_current_generation;
-#endif
+      _dbus_warn_check_failed ("dbus message iterator is NULL\n");
+      return FALSE;
     }
 
-  message->refcount.value = 1;
-  message->byte_order = DBUS_COMPILER_BYTE_ORDER;
-  message->locked = FALSE;
-  message->size_counters = NULL;
-  message->size_counter_delta = 0;
-  message->changed_stamp = 0;
-
-  if (!from_cache)
-    _dbus_data_slot_list_init (&message->slot_list);
-
-  if (from_cache)
+  if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
     {
-      _dbus_header_reinit (&message->header, message->byte_order);
-      _dbus_string_set_length (&message->body, 0);
+      if (iter->u.reader.byte_order != iter->message->byte_order)
+        {
+          _dbus_warn_check_failed ("dbus message changed byte order since iterator was created\n");
+          return FALSE;
+        }
+      /* because we swap the message into compiler order when you init an iter */
+      _dbus_assert (iter->u.reader.byte_order == DBUS_COMPILER_BYTE_ORDER);
     }
-  else
+  else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
     {
-      if (!_dbus_header_init (&message->header, message->byte_order))
+      if (iter->u.writer.byte_order != iter->message->byte_order)
         {
-          dbus_free (message);
-          return NULL;
+          _dbus_warn_check_failed ("dbus message changed byte order since append iterator was created\n");
+          return FALSE;
         }
+      /* because we swap the message into compiler order when you init an iter */
+      _dbus_assert (iter->u.writer.byte_order == DBUS_COMPILER_BYTE_ORDER);
+    }
+  else
+    {
+      _dbus_warn_check_failed ("dbus message iterator looks uninitialized or corrupted\n");
+      return FALSE;
+    }
 
-      if (!_dbus_string_init_preallocated (&message->body, 32))
-        {
-          _dbus_header_free (&message->header);
-          dbus_free (message);
-          return NULL;
-        }
+  if (iter->changed_stamp != iter->message->changed_stamp)
+    {
+      _dbus_warn_check_failed ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)\n");
+      return FALSE;
     }
 
-  return message;
+  return TRUE;
 }
+#endif /* DBUS_DISABLE_CHECKS */
 
 /**
- * Constructs a new message of the given message type.
- * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
- * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
- *
+ * Implementation of the varargs arg-getting functions.
+ * dbus_message_get_args() is the place to go for complete
+ * documentation.
+ *
+ * @see dbus_message_get_args
+ * @param iter the message iter
+ * @param error error to be filled in
+ * @param first_arg_type type of the first argument
+ * @param var_args return location for first argument, followed by list of type/location pairs
+ * @returns #FALSE if error was set
+ */
+dbus_bool_t
+_dbus_message_iter_get_args_valist (DBusMessageIter *iter,
+                                    DBusError       *error,
+                                    int              first_arg_type,
+                                    va_list          var_args)
+{
+  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
+  int spec_type, msg_type, i;
+  dbus_bool_t retval;
+
+  _dbus_assert (_dbus_message_iter_check (real));
+
+  retval = FALSE;
+
+  spec_type = first_arg_type;
+  i = 0;
+
+  while (spec_type != DBUS_TYPE_INVALID)
+    {
+      msg_type = dbus_message_iter_get_arg_type (iter);
+
+      if (msg_type != spec_type)
+       {
+          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
+                          "Argument %d is specified to be of type \"%s\", but "
+                          "is actually of type \"%s\"\n", i,
+                          _dbus_type_to_string (spec_type),
+                          _dbus_type_to_string (msg_type));
+
+          goto out;
+       }
+
+      if (dbus_type_is_basic (spec_type))
+        {
+          DBusBasicValue *ptr;
+
+          ptr = va_arg (var_args, DBusBasicValue*);
+
+          _dbus_assert (ptr != NULL);
+
+          _dbus_type_reader_read_basic (&real->u.reader,
+                                        ptr);
+        }
+      else if (spec_type == DBUS_TYPE_ARRAY)
+        {
+          int element_type;
+          int spec_element_type;
+          const DBusBasicValue **ptr;
+          int *n_elements_p;
+          DBusTypeReader array;
+
+          spec_element_type = va_arg (var_args, int);
+          element_type = _dbus_type_reader_get_element_type (&real->u.reader);
+
+          if (spec_element_type != element_type)
+            {
+              dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
+                              "Argument %d is specified to be an array of \"%s\", but "
+                              "is actually an array of \"%s\"\n",
+                              i,
+                              _dbus_type_to_string (spec_element_type),
+                              _dbus_type_to_string (element_type));
+
+              goto out;
+            }
+
+          if (dbus_type_is_fixed (spec_element_type))
+            {
+              ptr = va_arg (var_args, const DBusBasicValue**);
+              n_elements_p = va_arg (var_args, int*);
+
+              _dbus_assert (ptr != NULL);
+              _dbus_assert (n_elements_p != NULL);
+
+              _dbus_type_reader_recurse (&real->u.reader, &array);
+
+              _dbus_type_reader_read_fixed_multi (&array,
+                                                  ptr, n_elements_p);
+            }
+          else if (spec_element_type == DBUS_TYPE_STRING ||
+                   spec_element_type == DBUS_TYPE_SIGNATURE ||
+                   spec_element_type == DBUS_TYPE_OBJECT_PATH)
+            {
+              char ***str_array_p;
+              int n_elements;
+              char **str_array;
+
+              str_array_p = va_arg (var_args, char***);
+              n_elements_p = va_arg (var_args, int*);
+
+              _dbus_assert (str_array_p != NULL);
+              _dbus_assert (n_elements_p != NULL);
+
+              /* Count elements in the array */
+              _dbus_type_reader_recurse (&real->u.reader, &array);
+
+              n_elements = 0;
+              while (_dbus_type_reader_get_current_type (&array) != DBUS_TYPE_INVALID)
+                {
+                  ++n_elements;
+                  _dbus_type_reader_next (&array);
+                }
+
+              str_array = dbus_new0 (char*, n_elements + 1);
+              if (str_array == NULL)
+                {
+                  _DBUS_SET_OOM (error);
+                  goto out;
+                }
+
+              /* Now go through and dup each string */
+              _dbus_type_reader_recurse (&real->u.reader, &array);
+
+              i = 0;
+              while (i < n_elements)
+                {
+                  const char *s;
+                  _dbus_type_reader_read_basic (&array,
+                                                &s);
+                  
+                  str_array[i] = _dbus_strdup (s);
+                  if (str_array[i] == NULL)
+                    {
+                      dbus_free_string_array (str_array);
+                      _DBUS_SET_OOM (error);
+                      goto out;
+                    }
+                  
+                  ++i;
+                  
+                  if (!_dbus_type_reader_next (&array))
+                    _dbus_assert (i == n_elements);
+                }
+
+              _dbus_assert (_dbus_type_reader_get_current_type (&array) == DBUS_TYPE_INVALID);
+              _dbus_assert (i == n_elements);
+              _dbus_assert (str_array[i] == NULL);
+
+              *str_array_p = str_array;
+              *n_elements_p = n_elements;
+            }
+#ifndef DBUS_DISABLE_CHECKS
+          else
+            {
+              _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now\n",
+                          _DBUS_FUNCTION_NAME);
+              goto out;
+            }
+#endif
+        }
+#ifndef DBUS_DISABLE_CHECKS
+      else
+        {
+          _dbus_warn ("you can only read arrays and basic types with %s for now\n",
+                      _DBUS_FUNCTION_NAME);
+          goto out;
+        }
+#endif
+
+      spec_type = va_arg (var_args, int);
+      if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
+        {
+          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
+                          "Message has only %d arguments, but more were expected", i);
+          goto out;
+        }
+
+      i++;
+    }
+
+  retval = TRUE;
+
+ out:
+
+  return retval;
+}
+
+/** @} */
+
+/**
+ * @defgroup DBusMessage DBusMessage
+ * @ingroup  DBus
+ * @brief Message to be sent or received over a #DBusConnection.
+ *
+ * A DBusMessage is the most basic unit of communication over a
+ * DBusConnection. A DBusConnection represents a stream of messages
+ * received from a remote application, and a stream of messages
+ * sent to a remote application.
+ *
+ * A message has a message type, returned from
+ * dbus_message_get_type().  This indicates whether the message is a
+ * method call, a reply to a method call, a signal, or an error reply.
+ *
+ * A message has header fields such as the sender, destination, method
+ * or signal name, and so forth. DBusMessage has accessor functions for
+ * these, such as dbus_message_get_member().
+ *
+ * Convenience functions dbus_message_is_method_call(), dbus_message_is_signal(),
+ * and dbus_message_is_error() check several header fields at once and are
+ * slightly more efficient than checking the header fields with individual
+ * accessor functions.
+ *
+ * Finally, a message has arguments. The number and types of arguments
+ * are in the message's signature header field (accessed with
+ * dbus_message_get_signature()).  Simple argument values are usually
+ * retrieved with dbus_message_get_args() but more complex values such
+ * as structs may require the use of #DBusMessageIter.
+ *
+ * The D-Bus specification goes into some more detail about header fields and
+ * message types.
+ * 
+ * @{
+ */
+
+/**
+ * @typedef DBusMessage
+ *
+ * Opaque data type representing a message received from or to be
+ * sent to another application.
+ */
+
+/**
+ * Returns the serial of a message or 0 if none has been specified.
+ * The message's serial number is provided by the application sending
+ * the message and is used to identify replies to this message.
+ *
+ * All messages received on a connection will have a serial provided
+ * by the remote application.
+ *
+ * For messages you're sending, dbus_connection_send() will assign a
+ * serial and return it to you.
+ *
+ * @param message the message
+ * @returns the serial
+ */
+dbus_uint32_t
+dbus_message_get_serial (DBusMessage *message)
+{
+  _dbus_return_val_if_fail (message != NULL, 0);
+
+  return _dbus_header_get_serial (&message->header);
+}
+
+/**
+ * Sets the reply serial of a message (the serial of the message this
+ * is a reply to).
+ *
+ * @param message the message
+ * @param reply_serial the serial we're replying to
+ * @returns #FALSE if not enough memory
+ */
+dbus_bool_t
+dbus_message_set_reply_serial (DBusMessage   *message,
+                               dbus_uint32_t  reply_serial)
+{
+  _dbus_return_val_if_fail (message != NULL, FALSE);
+  _dbus_return_val_if_fail (!message->locked, FALSE);
+  _dbus_return_val_if_fail (reply_serial != 0, FALSE); /* 0 is invalid */
+
+  return _dbus_header_set_field_basic (&message->header,
+                                       DBUS_HEADER_FIELD_REPLY_SERIAL,
+                                       DBUS_TYPE_UINT32,
+                                       &reply_serial);
+}
+
+/**
+ * Returns the serial that the message is a reply to or 0 if none.
+ *
+ * @param message the message
+ * @returns the reply serial
+ */
+dbus_uint32_t
+dbus_message_get_reply_serial  (DBusMessage *message)
+{
+  dbus_uint32_t v_UINT32;
+
+  _dbus_return_val_if_fail (message != NULL, 0);
+
+  if (_dbus_header_get_field_basic (&message->header,
+                                    DBUS_HEADER_FIELD_REPLY_SERIAL,
+                                    DBUS_TYPE_UINT32,
+                                    &v_UINT32))
+    return v_UINT32;
+  else
+    return 0;
+}
+
+static void
+dbus_message_finalize (DBusMessage *message)
+{
+  _dbus_assert (message->refcount.value == 0);
+
+  /* This calls application callbacks! */
+  _dbus_data_slot_list_free (&message->slot_list);
+
+  _dbus_list_foreach (&message->size_counters,
+                      free_size_counter, message);
+  _dbus_list_clear (&message->size_counters);
+
+  _dbus_header_free (&message->header);
+  _dbus_string_free (&message->body);
+
+  _dbus_assert (message->refcount.value == 0);
+  
+  dbus_free (message);
+}
+
+static DBusMessage*
+dbus_message_new_empty_header (void)
+{
+  DBusMessage *message;
+  dbus_bool_t from_cache;
+
+  message = dbus_message_get_cached ();
+
+  if (message != NULL)
+    {
+      from_cache = TRUE;
+    }
+  else
+    {
+      from_cache = FALSE;
+      message = dbus_new (DBusMessage, 1);
+      if (message == NULL)
+        return NULL;
+#ifndef DBUS_DISABLE_CHECKS
+      message->generation = _dbus_current_generation;
+#endif
+    }
+  
+  message->refcount.value = 1;
+  message->byte_order = DBUS_COMPILER_BYTE_ORDER;
+  message->locked = FALSE;
+#ifndef DBUS_DISABLE_CHECKS
+  message->in_cache = FALSE;
+#endif
+  message->size_counters = NULL;
+  message->size_counter_delta = 0;
+  message->changed_stamp = 0;
+
+  if (!from_cache)
+    _dbus_data_slot_list_init (&message->slot_list);
+
+  if (from_cache)
+    {
+      _dbus_header_reinit (&message->header, message->byte_order);
+      _dbus_string_set_length (&message->body, 0);
+    }
+  else
+    {
+      if (!_dbus_header_init (&message->header, message->byte_order))
+        {
+          dbus_free (message);
+          return NULL;
+        }
+
+      if (!_dbus_string_init_preallocated (&message->body, 32))
+        {
+          _dbus_header_free (&message->header);
+          dbus_free (message);
+          return NULL;
+        }
+    }
+
+  return message;
+}
+
+/**
+ * Constructs a new message of the given message type.
+ * Types include #DBUS_MESSAGE_TYPE_METHOD_CALL,
+ * #DBUS_MESSAGE_TYPE_SIGNAL, and so forth.
+ *
+ * Usually you want to use dbus_message_new_method_call(),
+ * dbus_message_new_method_return(), dbus_message_new_signal(),
+ * or dbus_message_new_error() instead.
+ * 
  * @param message_type type of message
- * @returns new message or #NULL If no memory
+ * @returns new message or #NULL if no memory
  */
 DBusMessage*
 dbus_message_new (int message_type)
@@ -723,18 +1046,22 @@ dbus_message_new (int message_type)
  * Constructs a new message to invoke a method on a remote
  * object. Returns #NULL if memory can't be allocated for the
  * message. The destination may be #NULL in which case no destination
- * is set; this is appropriate when using D-BUS in a peer-to-peer
+ * is set; this is appropriate when using D-Bus in a peer-to-peer
  * context (no message bus). The interface may be #NULL, which means
  * that if multiple methods with the given name exist it is undefined
  * which one will be invoked.
-  *
+ *
+ * The path and method names may not be #NULL.
+ *
+ * Destination, path, interface, and method name can't contain
+ * any invalid characters (see the D-Bus specification).
+ * 
  * @param destination name that the message should be sent to or #NULL
  * @param path object path the message should be sent to
- * @param interface interface to invoke method on
+ * @param interface interface to invoke method on, or #NULL
  * @param method method to invoke
  *
  * @returns a new DBusMessage, free with dbus_message_unref()
- * @see dbus_message_unref()
  */
 DBusMessage*
 dbus_message_new_method_call (const char *destination,
@@ -772,10 +1099,8 @@ dbus_message_new_method_call (const char *destination,
  * Constructs a message that is a reply to a method call. Returns
  * #NULL if memory can't be allocated for the message.
  *
- * @param method_call the message which the created
- * message is a reply to.
+ * @param method_call the message being replied to
  * @returns a new DBusMessage, free with dbus_message_unref()
- * @see dbus_message_new_method_call(), dbus_message_unref()
  */
 DBusMessage*
 dbus_message_new_method_return (DBusMessage *method_call)
@@ -816,14 +1141,16 @@ dbus_message_new_method_return (DBusMessage *method_call)
 /**
  * Constructs a new message representing a signal emission. Returns
  * #NULL if memory can't be allocated for the message.  A signal is
- * identified by its originating interface, and the name of the
- * signal.
+ * identified by its originating object path, interface, and the name
+ * of the signal.
  *
+ * Path, interface, and signal name must all be valid (the D-Bus
+ * specification defines the syntax of these fields).
+ * 
  * @param path the path to the object emitting the signal
  * @param interface the interface the signal is emitted from
  * @param name name of the signal
  * @returns a new DBusMessage, free with dbus_message_unref()
- * @see dbus_message_unref()
  */
 DBusMessage*
 dbus_message_new_signal (const char *path,
@@ -857,13 +1184,18 @@ dbus_message_new_signal (const char *path,
 }
 
 /**
- * Creates a new message that is an error reply to a certain message.
- * Error replies are possible in response to method calls primarily.
+ * Creates a new message that is an error reply to another message.
+ * Error replies are most common in response to method calls, but
+ * can be returned in reply to any message.
  *
- * @param reply_to the original message
+ * The error name must be a valid error name according to the syntax
+ * given in the D-Bus specification. If you don't want to make
+ * up an error name just use #DBUS_ERROR_FAILED.
+ *
+ * @param reply_to the message we're replying to
  * @param error_name the error name
- * @param error_message the error message string or #NULL for none
- * @returns a new error message
+ * @param error_message the error message string (or #NULL for none, but please give a message)
+ * @returns a new error message object, free with dbus_message_unref()
  */
 DBusMessage*
 dbus_message_new_error (DBusMessage *reply_to,
@@ -921,9 +1253,15 @@ dbus_message_new_error (DBusMessage *reply_to,
 }
 
 /**
- * Creates a new message that is an error reply to a certain message.
- * Error replies are possible in response to method calls primarily.
+ * Creates a new message that is an error reply to another message, allowing
+ * you to use printf formatting.
  *
+ * See dbus_message_new_error() for details - this function is the same
+ * aside from the printf formatting.
+ *
+ * @todo add _DBUS_GNUC_PRINTF to this (requires moving _DBUS_GNUC_PRINTF to
+ * public header, see DBUS_DEPRECATED for an example)
+ * 
  * @param reply_to the original message
  * @param error_name the error name
  * @param error_format the error message format as with printf
@@ -970,8 +1308,8 @@ dbus_message_new_error_printf (DBusMessage *reply_to,
  * outgoing message queue and thus not modifiable) the new message
  * will not be locked.
  *
- * @param message the message.
- * @returns the new message.
+ * @param message the message
+ * @returns the new message.or #NULL if not enough memory
  */
 DBusMessage *
 dbus_message_copy (const DBusMessage *message)
@@ -1023,7 +1361,7 @@ dbus_message_copy (const DBusMessage *message)
 /**
  * Increments the reference count of a DBusMessage.
  *
- * @param message The message
+ * @param message the message
  * @returns the message
  * @see dbus_message_unref
  */
@@ -1034,7 +1372,8 @@ dbus_message_ref (DBusMessage *message)
 
   _dbus_return_val_if_fail (message != NULL, NULL);
   _dbus_return_val_if_fail (message->generation == _dbus_current_generation, NULL);
-
+  _dbus_return_val_if_fail (!message->in_cache, NULL);
+  
   old_refcount = _dbus_atomic_inc (&message->refcount);
   _dbus_assert (old_refcount >= 1);
 
@@ -1042,9 +1381,10 @@ dbus_message_ref (DBusMessage *message)
 }
 
 /**
- * Decrements the reference count of a DBusMessage.
+ * Decrements the reference count of a DBusMessage, freeing the
+ * message if the count reaches 0.
  *
- * @param message The message
+ * @param message the message
  * @see dbus_message_ref
  */
 void
@@ -1054,6 +1394,7 @@ dbus_message_unref (DBusMessage *message)
 
   _dbus_return_if_fail (message != NULL);
   _dbus_return_if_fail (message->generation == _dbus_current_generation);
+  _dbus_return_if_fail (!message->in_cache);
 
   old_refcount = _dbus_atomic_dec (&message->refcount);
 
@@ -1071,9 +1412,7 @@ dbus_message_unref (DBusMessage *message)
  * #DBUS_MESSAGE_TYPE_METHOD_CALL, #DBUS_MESSAGE_TYPE_METHOD_RETURN,
  * #DBUS_MESSAGE_TYPE_ERROR, #DBUS_MESSAGE_TYPE_SIGNAL, but other
  * types are allowed and all code must silently ignore messages of
- * unknown type. DBUS_MESSAGE_TYPE_INVALID will never be returned,
- * however.
- *
+ * unknown type. #DBUS_MESSAGE_TYPE_INVALID will never be returned.
  *
  * @param message the message
  * @returns the type of the message
@@ -1095,25 +1434,17 @@ dbus_message_get_type (DBusMessage *message)
  * rather than this function.
  *
  * To append a basic type, specify its type code followed by the
- * value. For example:
+ * address of the value. For example:
  *
  * @code
- * DBUS_TYPE_INT32, 42,
- * DBUS_TYPE_STRING, "Hello World"
- * @endcode
- * or
- * @code
- * dbus_int32_t val = 42;
- * DBUS_TYPE_INT32, val
- * @endcode
  *
- * Be sure that your provided value is the right size. For example, this
- * won't work:
- * @code
- * DBUS_TYPE_INT64, 42
+ * dbus_int32_t v_INT32 = 42;
+ * const char *v_STRING = "Hello World";
+ * dbus_message_append_args (message,
+ *                           DBUS_TYPE_INT32, &v_INT32,
+ *                           DBUS_TYPE_STRING, &v_STRING,
+ *                           DBUS_TYPE_INVALID);
  * @endcode
- * Because the "42" will be a 32-bit integer. You need to cast to
- * 64-bit.
  *
  * To append an array of fixed-length basic types, pass in the
  * DBUS_TYPE_ARRAY typecode, the element typecode, the address of
@@ -1122,7 +1453,9 @@ dbus_message_get_type (DBusMessage *message)
  * @code
  * const dbus_int32_t array[] = { 1, 2, 3 };
  * const dbus_int32_t *v_ARRAY = array;
- * DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3
+ * dbus_message_append_args (message,
+ *                           DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY, 3,
+ *                           DBUS_TYPE_INVALID);
  * @endcode
  *
  * @warning in C, given "int array[]", "&array == array" (the
@@ -1133,7 +1466,11 @@ dbus_message_get_type (DBusMessage *message)
  * const char *array = "Hello" and then use &array though.
  *
  * The last argument to this function must be #DBUS_TYPE_INVALID,
- * marking the end of the argument list.
+ * marking the end of the argument list. If you don't do this
+ * then libdbus won't know to stop and will read invalid memory.
+ *
+ * String/signature/path arrays should be passed in as "const char***
+ * address_of_array" and "int n_elements"
  *
  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
  *
@@ -1165,8 +1502,7 @@ dbus_message_append_args (DBusMessage *message,
 }
 
 /**
- * This function takes a va_list for use by language bindings.
- * It's otherwise the same as dbus_message_append_args().
+ * Like dbus_message_append_args() but takes a va_list for use by language bindings.
  *
  * @todo for now, if this function fails due to OOM it will leave
  * the message half-written and you have to discard the message
@@ -1194,7 +1530,7 @@ dbus_message_append_args_valist (DBusMessage *message,
 
   while (type != DBUS_TYPE_INVALID)
     {
-      if (_dbus_type_is_basic (type))
+      if (dbus_type_is_basic (type))
         {
           const DBusBasicValue *value;
           value = va_arg (var_args, const DBusBasicValue*);
@@ -1207,39 +1543,68 @@ dbus_message_append_args_valist (DBusMessage *message,
       else if (type == DBUS_TYPE_ARRAY)
         {
           int element_type;
-          const DBusBasicValue **value;
-          int n_elements;
           DBusMessageIter array;
           char buf[2];
 
           element_type = va_arg (var_args, int);
+              
+          buf[0] = element_type;
+          buf[1] = '\0';
+          if (!dbus_message_iter_open_container (&iter,
+                                                 DBUS_TYPE_ARRAY,
+                                                 buf,
+                                                 &array))
+            goto failed;
+          
+          if (dbus_type_is_fixed (element_type))
+            {
+              const DBusBasicValue **value;
+              int n_elements;
+
+              value = va_arg (var_args, const DBusBasicValue**);
+              n_elements = va_arg (var_args, int);
+              
+              if (!dbus_message_iter_append_fixed_array (&array,
+                                                         element_type,
+                                                         value,
+                                                         n_elements)) {
+                dbus_message_iter_abandon_container (&iter, &array);
+                goto failed;
+              }
+            }
+          else if (element_type == DBUS_TYPE_STRING ||
+                   element_type == DBUS_TYPE_SIGNATURE ||
+                   element_type == DBUS_TYPE_OBJECT_PATH)
+            {
+              const char ***value_p;
+              const char **value;
+              int n_elements;
+              int i;
+              
+              value_p = va_arg (var_args, const char***);
+              n_elements = va_arg (var_args, int);
 
-#ifndef DBUS_DISABLE_CHECKS
-          if (!_dbus_type_is_fixed (element_type))
+              value = *value_p;
+              
+              i = 0;
+              while (i < n_elements)
+                {
+                  if (!dbus_message_iter_append_basic (&array,
+                                                       element_type,
+                                                       &value[i])) {
+                    dbus_message_iter_abandon_container (&iter, &array);
+                    goto failed;
+                  }
+                  ++i;
+                }
+            }
+          else
             {
               _dbus_warn ("arrays of %s can't be appended with %s for now\n",
                           _dbus_type_to_string (element_type),
                           _DBUS_FUNCTION_NAME);
               goto failed;
             }
-#endif
-
-          value = va_arg (var_args, const DBusBasicValue**);
-          n_elements = va_arg (var_args, int);
-
-          buf[0] = element_type;
-          buf[1] = '\0';
-          if (!dbus_message_iter_open_container (&iter,
-                                                 DBUS_TYPE_ARRAY,
-                                                 buf,
-                                                 &array))
-            goto failed;
-
-          if (!dbus_message_iter_append_fixed_array (&array,
-                                                     element_type,
-                                                     value,
-                                                     n_elements))
-            goto failed;
 
           if (!dbus_message_iter_close_container (&iter, &array))
             goto failed;
@@ -1273,18 +1638,22 @@ dbus_message_append_args_valist (DBusMessage *message,
  * In addition to those types, arrays of string, object path, and
  * signature are supported; but these are returned as allocated memory
  * and must be freed with dbus_free_string_array(), while the other
- * types are returned as const references.
+ * types are returned as const references. To get a string array
+ * pass in "char ***array_location" and "int *n_elements"
  *
  * The variable argument list should contain the type of the argument
  * followed by a pointer to where the value should be stored. The list
  * is terminated with #DBUS_TYPE_INVALID.
  *
- * The returned values are constant; do not free them. They point
- * into the #DBusMessage.
+ * Except for string arrays, the returned values are constant; do not
+ * free them. They point into the #DBusMessage.
  *
  * If the requested arguments are not present, or do not have the
  * requested types, then an error will be set.
  *
+ * If more arguments than requested are present, the requested
+ * arguments are returned and the extra arguments are ignored.
+ * 
  * @todo support DBUS_TYPE_STRUCT and DBUS_TYPE_VARIANT and complex arrays
  *
  * @param message the message
@@ -1313,8 +1682,7 @@ dbus_message_get_args (DBusMessage     *message,
 }
 
 /**
- * This function takes a va_list for use by language bindings. It is
- * otherwise the same as dbus_message_get_args().
+ * Like dbus_message_get_args but takes a va_list for use by language bindings.
  *
  * @see dbus_message_get_args
  * @param message the message
@@ -1345,6 +1713,11 @@ _dbus_message_iter_init_common (DBusMessage         *message,
 {
   _dbus_assert (sizeof (DBusMessageRealIter) <= sizeof (DBusMessageIter));
 
+  /* Since the iterator will read or write who-knows-what from the
+   * message, we need to get in the right byte order
+   */
+  ensure_byte_order (message);
+  
   real->message = message;
   real->changed_stamp = message->changed_stamp;
   real->iter_type = iter_type;
@@ -1355,6 +1728,20 @@ _dbus_message_iter_init_common (DBusMessage         *message,
  * Initializes a #DBusMessageIter for reading the arguments of the
  * message passed in.
  *
+ * When possible, dbus_message_get_args() is much more convenient.
+ * Some types of argument can only be read with #DBusMessageIter
+ * however.
+ *
+ * The easiest way to iterate is like this: 
+ * @code
+ * dbus_message_iter_init (message, &iter);
+ * while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID)
+ *   dbus_message_iter_next (&iter);
+ * @endcode
+ *
+ * #DBusMessageIter contains no allocated memory; it need not be
+ * freed, and can be copied by assignment or memcpy().
+ * 
  * @param message the message
  * @param iter pointer to an iterator to initialize
  * @returns #FALSE if the message has no arguments
@@ -1381,57 +1768,14 @@ dbus_message_iter_init (DBusMessage     *message,
                           &message->body,
                           0);
 
-  return _dbus_type_reader_has_next (&real->u.reader);
-}
-
-#ifndef DBUS_DISABLE_CHECKS
-static dbus_bool_t
-_dbus_message_iter_check (DBusMessageRealIter *iter)
-{
-  if (iter == NULL)
-    {
-      _dbus_warn ("dbus message iterator is NULL\n");
-      return FALSE;
-    }
-
-  if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_READER)
-    {
-      if (iter->u.reader.byte_order != iter->message->byte_order)
-        {
-          _dbus_warn ("dbus message changed byte order since iterator was created\n");
-          return FALSE;
-        }
-    }
-  else if (iter->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER)
-    {
-      if (iter->u.writer.byte_order != iter->message->byte_order)
-        {
-          _dbus_warn ("dbus message changed byte order since append iterator was created\n");
-          return FALSE;
-        }
-    }
-  else
-    {
-      _dbus_warn ("dbus message iterator looks uninitialized or corrupted\n");
-      return FALSE;
-    }
-
-  if (iter->changed_stamp != iter->message->changed_stamp)
-    {
-      _dbus_warn ("dbus message iterator invalid because the message has been modified (or perhaps the iterator is just uninitialized)\n");
-      return FALSE;
-    }
-
-  return TRUE;
+  return _dbus_type_reader_get_current_type (&real->u.reader) != DBUS_TYPE_INVALID;
 }
-#endif /* DBUS_DISABLE_CHECKS */
 
 /**
  * Checks if an iterator has any more fields.
  *
  * @param iter the message iter
- * @returns #TRUE if there are more fields
- * following
+ * @returns #TRUE if there are more fields following
  */
 dbus_bool_t
 dbus_message_iter_has_next (DBusMessageIter *iter)
@@ -1520,6 +1864,16 @@ dbus_message_iter_get_element_type (DBusMessageIter *iter)
  * you won't be able to recurse further. There's no array of int32 to
  * recurse into.
  *
+ * If a container is an array of fixed-length types, it is much more
+ * efficient to use dbus_message_iter_get_fixed_array() to get the
+ * whole array in one shot, rather than individually walking over the
+ * array elements.
+ *
+ * Be sure you have somehow checked that
+ * dbus_message_iter_get_arg_type() matches the type you are expecting
+ * to recurse into. Results of this function are undefined if there is
+ * no container to recurse into at the current iterator position.
+ *
  * @param iter the message iterator
  * @param sub the sub-iterator to initialize
  */
@@ -1538,6 +1892,43 @@ dbus_message_iter_recurse (DBusMessageIter  *iter,
 }
 
 /**
+ * Returns the current signature of a message iterator.  This
+ * is useful primarily for dealing with variants; one can
+ * recurse into a variant and determine the signature of
+ * the variant's value.
+ *
+ * The returned string must be freed with dbus_free().
+ * 
+ * @param iter the message iterator
+ * @returns the contained signature, or NULL if out of memory
+ */
+char *
+dbus_message_iter_get_signature (DBusMessageIter *iter)
+{
+  const DBusString *sig;
+  DBusString retstr;
+  char *ret;
+  int start, len;
+  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
+
+  _dbus_return_val_if_fail (_dbus_message_iter_check (real), NULL);
+
+  if (!_dbus_string_init (&retstr))
+    return NULL;
+
+  _dbus_type_reader_get_signature (&real->u.reader, &sig,
+                                  &start, &len);
+  if (!_dbus_string_append_len (&retstr,
+                               _dbus_string_get_const_data (sig) + start,
+                               len))
+    return NULL;
+  if (!_dbus_string_steal_data (&retstr, &ret))
+    return NULL;
+  _dbus_string_free (&retstr);
+  return ret;
+}
+
+/**
  * Reads a basic-typed value from the message iterator.
  * Basic types are the non-containers such as integer and string.
  *
@@ -1546,28 +1937,33 @@ dbus_message_iter_recurse (DBusMessageIter  *iter,
  * and for string a "const char**". The returned value is
  * by reference and should not be freed.
  *
- * All returned values are guaranteed to fit in 8 bytes. So you can
+ * Be sure you have somehow checked that
+ * dbus_message_iter_get_arg_type() matches the type you are
+ * expecting, or you'll crash when you try to use an integer as a
+ * string or something.
+ *
+ * To read any container type (array, struct, dict) you will need
+ * to recurse into the container with dbus_message_iter_recurse().
+ * If the container is an array of fixed-length values, you can
+ * get all the array elements at once with
+ * dbus_message_iter_get_fixed_array(). Otherwise, you have to
+ * iterate over the container's contents one value at a time.
+ * 
+ * All basic-typed values are guaranteed to fit in 8 bytes. So you can
  * write code like this:
  *
  * @code
- * #ifdef DBUS_HAVE_INT64
  * dbus_uint64_t value;
  * int type;
  * dbus_message_iter_get_basic (&read_iter, &value);
  * type = dbus_message_iter_get_arg_type (&read_iter);
  * dbus_message_iter_append_basic (&write_iter, type, &value);
- * #endif
  * @endcode
  *
- * To avoid the #DBUS_HAVE_INT64 conditional, create a struct or
- * something that occupies at least 8 bytes, e.g. you could use a
- * struct with two int32 values in it. dbus_uint64_t is just one
- * example of a type that's large enough to hold any possible value.
- *
- * Be sure you have somehow checked that
- * dbus_message_iter_get_arg_type() matches the type you are
- * expecting, or you'll crash when you try to use an integer as a
- * string or something.
+ * On some really obscure platforms dbus_uint64_t might not exist, if
+ * you need to worry about this you will know.  dbus_uint64_t is just
+ * one example of a type that's large enough to hold any possible
+ * value, you could use a struct or char[8] instead if you like.
  *
  * @param iter the iterator
  * @param value location to store the value
@@ -1586,219 +1982,79 @@ dbus_message_iter_get_basic (DBusMessageIter  *iter,
 }
 
 /**
- * Reads a block of fixed-length values from the message iterator.
- * Fixed-length values are those basic types that are not string-like,
- * such as integers, bool, double. The block read will be from the
- * current position in the array until the end of the array.
- *
- * The value argument should be the address of a location to store the
- * returned array. So for int32 it should be a "const dbus_int32_t**"
- * The returned value is by reference and should not be freed.
- *
+ * Returns the number of bytes in the array as marshaled in the wire
+ * protocol. The iterator must currently be inside an array-typed
+ * value.
+ *
+ * This function is deprecated on the grounds that it is stupid.  Why
+ * would you want to know how many bytes are in the array as marshaled
+ * in the wire protocol?  For now, use the n_elements returned from
+ * dbus_message_iter_get_fixed_array() instead, or iterate over the
+ * array values and count them.
+ *
+ * @todo introduce a variant of this get_n_elements that returns
+ * the number of elements, though with a non-fixed array it will not
+ * be very efficient, so maybe it's not good.
+ * 
  * @param iter the iterator
- * @param value location to store the block
- * @param n_elements number of elements in the block
- */
-void
-dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
-                                   void             *value,
-                                   int              *n_elements)
-{
-  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
-
-  _dbus_return_if_fail (_dbus_message_iter_check (real));
-  _dbus_return_if_fail (value != NULL);
-  _dbus_return_if_fail (_dbus_type_is_fixed (_dbus_type_reader_get_element_type (&real->u.reader)));
-
-  _dbus_type_reader_read_fixed_multi (&real->u.reader,
-                                      value, n_elements);
-}
-
-/**
- * This function takes a va_list for use by language bindings and is
- * otherwise the same as dbus_message_iter_get_args().
- * dbus_message_get_args() is the place to go for complete
- * documentation.
- *
- * @see dbus_message_get_args
- * @param iter the message iter
- * @param error error to be filled in
- * @param first_arg_type type of the first argument
- * @param var_args return location for first argument, followed by list of type/location pairs
- * @returns #FALSE if error was set
+ * @returns the number of bytes in the array
  */
-dbus_bool_t
-_dbus_message_iter_get_args_valist (DBusMessageIter *iter,
-                                    DBusError       *error,
-                                    int              first_arg_type,
-                                    va_list          var_args)
+int
+dbus_message_iter_get_array_len (DBusMessageIter *iter)
 {
-  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
-  int spec_type, msg_type, i;
-  dbus_bool_t retval;
-
-  _dbus_assert (_dbus_message_iter_check (real));
-
-  retval = FALSE;
-
-  spec_type = first_arg_type;
-  i = 0;
-
-  while (spec_type != DBUS_TYPE_INVALID)
-    {
-      msg_type = dbus_message_iter_get_arg_type (iter);
-
-      if (msg_type != spec_type)
-       {
-          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
-                          "Argument %d is specified to be of type \"%s\", but "
-                          "is actually of type \"%s\"\n", i,
-                          _dbus_type_to_string (spec_type),
-                          _dbus_type_to_string (msg_type));
-
-          goto out;
-       }
-
-      if (_dbus_type_is_basic (spec_type))
-        {
-          DBusBasicValue *ptr;
-
-          ptr = va_arg (var_args, DBusBasicValue*);
-
-          _dbus_assert (ptr != NULL);
-
-          _dbus_type_reader_read_basic (&real->u.reader,
-                                        ptr);
-        }
-      else if (spec_type == DBUS_TYPE_ARRAY)
-        {
-          int element_type;
-          int spec_element_type;
-          const DBusBasicValue **ptr;
-          int *n_elements_p;
-          DBusTypeReader array;
-
-          spec_element_type = va_arg (var_args, int);
-          element_type = _dbus_type_reader_get_element_type (&real->u.reader);
-
-          if (spec_element_type != element_type)
-            {
-              dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
-                              "Argument %d is specified to be an array of \"%s\", but "
-                              "is actually an array of \"%s\"\n",
-                              i,
-                              _dbus_type_to_string (spec_element_type),
-                              _dbus_type_to_string (element_type));
-
-              goto out;
-            }
-
-          if (_dbus_type_is_fixed (spec_element_type))
-            {
-              ptr = va_arg (var_args, const DBusBasicValue**);
-              n_elements_p = va_arg (var_args, int*);
-
-              _dbus_assert (ptr != NULL);
-              _dbus_assert (n_elements_p != NULL);
-
-              _dbus_type_reader_recurse (&real->u.reader, &array);
-
-              _dbus_type_reader_read_fixed_multi (&array,
-                                                  ptr, n_elements_p);
-            }
-          else if (spec_element_type == DBUS_TYPE_STRING ||
-                   spec_element_type == DBUS_TYPE_SIGNATURE ||
-                   spec_element_type == DBUS_TYPE_OBJECT_PATH)
-            {
-              char ***str_array_p;
-              int i;
-              char **str_array;
-
-              str_array_p = va_arg (var_args, char***);
-              n_elements_p = va_arg (var_args, int*);
-
-              _dbus_assert (str_array_p != NULL);
-              _dbus_assert (n_elements_p != NULL);
-
-              /* Count elements in the array */
-              _dbus_type_reader_recurse (&real->u.reader, &array);
-
-              i = 0;
-              if (_dbus_type_reader_has_next (&array))
-                {
-                  while (_dbus_type_reader_next (&array))
-                    ++i;
-                }
-
-              str_array = dbus_new0 (char*, i + 1);
-              if (str_array == NULL)
-                {
-                  _DBUS_SET_OOM (error);
-                  goto out;
-                }
-
-              /* Now go through and dup each string */
-              _dbus_type_reader_recurse (&real->u.reader, &array);
-
-              i = 0;
-              if (_dbus_type_reader_has_next (&array))
-                {
-                  do
-                    {
-                      const char *s;
-                      _dbus_type_reader_read_basic (&array,
-                                                    &s);
-
-                      str_array[i] = _dbus_strdup (s);
-                      if (str_array[i] == NULL)
-                        {
-                          dbus_free_string_array (str_array);
-                          _DBUS_SET_OOM (error);
-                          goto out;
-                        }
-
-                      ++i;
-                    }
-                  while (_dbus_type_reader_next (&array));
-                }
-
-              *str_array_p = str_array;
-              *n_elements_p = i;
-            }
-#ifndef DBUS_DISABLE_CHECKS
-          else
-            {
-              _dbus_warn ("you can't read arrays of container types (struct, variant, array) with %s for now\n",
-                          _DBUS_FUNCTION_NAME);
-              goto out;
-            }
-#endif
-        }
-#ifndef DBUS_DISABLE_CHECKS
-      else
-        {
-          _dbus_warn ("you can only read arrays and basic types with %s for now\n",
-                      _DBUS_FUNCTION_NAME);
-          goto out;
-        }
-#endif
+  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
 
-      spec_type = va_arg (var_args, int);
-      if (!_dbus_type_reader_next (&real->u.reader) && spec_type != DBUS_TYPE_INVALID)
-        {
-          dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
-                          "Message has only %d arguments, but more were expected", i);
-          goto out;
-        }
+  _dbus_return_val_if_fail (_dbus_message_iter_check (real), 0);
 
-      i++;
-    }
+  return _dbus_type_reader_get_array_length (&real->u.reader);
+}
 
-  retval = TRUE;
+/**
+ * Reads a block of fixed-length values from the message iterator.
+ * Fixed-length values are those basic types that are not string-like,
+ * such as integers, bool, double. The returned block will be from the
+ * current position in the array until the end of the array.
+ *
+ * The message iter should be "in" the array (that is, you recurse into the
+ * array, and then you call dbus_message_iter_get_fixed_array() on the
+ * "sub-iterator" created by dbus_message_iter_recurse()).
+ *
+ * The value argument should be the address of a location to store the
+ * returned array. So for int32 it should be a "const dbus_int32_t**"
+ * The returned value is by reference and should not be freed.
+ * 
+ * This function should only be used if dbus_type_is_fixed() returns
+ * #TRUE for the element type.
+ *
+ * If an array's elements are not fixed in size, you have to recurse
+ * into the array with dbus_message_iter_recurse() and read the
+ * elements one by one.
+ * 
+ * Because the array is not copied, this function runs in constant
+ * time and is fast; it's much preferred over walking the entire array
+ * with an iterator. (However, you can always use
+ * dbus_message_iter_recurse(), even for fixed-length types;
+ * dbus_message_iter_get_fixed_array() is just an optimization.)
+ * 
+ * @param iter the iterator
+ * @param value location to store the block
+ * @param n_elements number of elements in the block
+ */
+void
+dbus_message_iter_get_fixed_array (DBusMessageIter  *iter,
+                                   void             *value,
+                                   int              *n_elements)
+{
+  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
+  int subtype = _dbus_type_reader_get_current_type(&real->u.reader);
 
- out:
+  _dbus_return_if_fail (_dbus_message_iter_check (real));
+  _dbus_return_if_fail (value != NULL);
+  _dbus_return_if_fail ((subtype == DBUS_TYPE_INVALID) ||
+                         dbus_type_is_fixed (subtype));
 
-  return retval;
+  _dbus_type_reader_read_fixed_multi (&real->u.reader,
+                                      value, n_elements);
 }
 
 /**
@@ -1806,8 +2062,8 @@ _dbus_message_iter_get_args_valist (DBusMessageIter *iter,
  * of a message.
  *
  * @todo If appending any of the arguments fails due to lack of
- * memory, generally the message is hosed and you have to start over
- * building the whole message.
+ * memory, the message is hosed and you have to start over building
+ * the whole message.
  *
  * @param message the message
  * @param iter pointer to an iterator to initialize
@@ -1948,6 +2204,35 @@ _dbus_message_iter_close_signature (DBusMessageRealIter *real)
   return retval;
 }
 
+/**
+ * Frees the signature string and marks the iterator as not having a
+ * type_str anymore.  Since the new signature is not set, the message
+ * will generally be hosed after this is called.
+ *
+ * @param real an iterator without a type_str
+ */
+static void
+_dbus_message_iter_abandon_signature (DBusMessageRealIter *real)
+{
+  DBusString *str;
+
+  _dbus_assert (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
+  _dbus_assert (real->u.writer.type_str != NULL);
+  _dbus_assert (real->sig_refcount > 0);
+
+  real->sig_refcount -= 1;
+
+  if (real->sig_refcount > 0)
+    return;
+  _dbus_assert (real->sig_refcount == 0);
+
+  str = real->u.writer.type_str;
+
+  _dbus_type_writer_remove_types (&real->u.writer);
+  _dbus_string_free (str);
+  dbus_free (str);
+}
+
 #ifndef DBUS_DISABLE_CHECKS
 static dbus_bool_t
 _dbus_message_iter_append_check (DBusMessageRealIter *iter)
@@ -1957,7 +2242,7 @@ _dbus_message_iter_append_check (DBusMessageRealIter *iter)
 
   if (iter->message->locked)
     {
-      _dbus_warn ("dbus append iterator can't be used: message is locked (has already been sent)\n");
+      _dbus_warn_check_failed ("dbus append iterator can't be used: message is locked (has already been sent)\n");
       return FALSE;
     }
 
@@ -1990,7 +2275,7 @@ dbus_message_iter_append_basic (DBusMessageIter *iter,
 
   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
-  _dbus_return_val_if_fail (_dbus_type_is_basic (type), FALSE);
+  _dbus_return_val_if_fail (dbus_type_is_basic (type), FALSE);
   _dbus_return_val_if_fail (value != NULL, FALSE);
 
   if (!_dbus_message_iter_open_signature (real))
@@ -2050,7 +2335,7 @@ dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
 
   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
-  _dbus_return_val_if_fail (_dbus_type_is_fixed (element_type), FALSE);
+  _dbus_return_val_if_fail (dbus_type_is_fixed (element_type), FALSE);
   _dbus_return_val_if_fail (real->u.writer.container_type == DBUS_TYPE_ARRAY, FALSE);
   _dbus_return_val_if_fail (value != NULL, FALSE);
   _dbus_return_val_if_fail (n_elements >= 0, FALSE);
@@ -2070,10 +2355,10 @@ dbus_message_iter_append_fixed_array (DBusMessageIter *iter,
  * dbus_message_iter_close_container(). Container types are for
  * example struct, variant, and array. For variants, the
  * contained_signature should be the type of the single value inside
- * the variant. For structs, contained_signature should be #NULL; it
- * will be set to whatever types you write into the struct.  For
- * arrays, contained_signature should be the type of the array
- * elements.
+ * the variant. For structs and dict entries, contained_signature
+ * should be #NULL; it will be set to whatever types you write into
+ * the struct.  For arrays, contained_signature should be the type of
+ * the array elements.
  *
  * @todo If this fails due to lack of memory, the message is hosed and
  * you have to start over building the whole message.
@@ -2096,22 +2381,47 @@ dbus_message_iter_open_container (DBusMessageIter *iter,
 
   _dbus_return_val_if_fail (_dbus_message_iter_append_check (real), FALSE);
   _dbus_return_val_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER, FALSE);
-  _dbus_return_val_if_fail (_dbus_type_is_container (type), FALSE);
+  _dbus_return_val_if_fail (dbus_type_is_container (type), FALSE);
   _dbus_return_val_if_fail (sub != NULL, FALSE);
   _dbus_return_val_if_fail ((type == DBUS_TYPE_STRUCT &&
                              contained_signature == NULL) ||
-                            contained_signature != NULL, FALSE);
+                            (type == DBUS_TYPE_DICT_ENTRY &&
+                             contained_signature == NULL) ||
+                            (type == DBUS_TYPE_VARIANT &&
+                             contained_signature != NULL) ||
+                            (type == DBUS_TYPE_ARRAY &&
+                             contained_signature != NULL), FALSE);
+  
+  /* this would fail if the contained_signature is a dict entry, since
+   * dict entries are invalid signatures standalone (they must be in
+   * an array)
+   */
+  _dbus_return_val_if_fail ((type == DBUS_TYPE_ARRAY && contained_signature && *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) ||
+                            (contained_signature == NULL ||
+                             _dbus_check_is_valid_signature (contained_signature)),
+                            FALSE);
 
   if (!_dbus_message_iter_open_signature (real))
     return FALSE;
 
-  _dbus_string_init_const (&contained_str, contained_signature);
-
   *real_sub = *real;
-  return _dbus_type_writer_recurse (&real->u.writer,
-                                    type,
-                                    &contained_str, 0,
-                                    &real_sub->u.writer);
+
+  if (contained_signature != NULL)
+    {
+      _dbus_string_init_const (&contained_str, contained_signature);
+
+      return _dbus_type_writer_recurse (&real->u.writer,
+                                        type,
+                                        &contained_str, 0,
+                                        &real_sub->u.writer);
+    }
+  else
+    {
+      return _dbus_type_writer_recurse (&real->u.writer,
+                                        type,
+                                        NULL, 0,
+                                        &real_sub->u.writer);
+    } 
 }
 
 
@@ -2151,6 +2461,32 @@ dbus_message_iter_close_container (DBusMessageIter *iter,
 }
 
 /**
+ * Abandons creation of a contained-typed value and frees resources created
+ * by dbus_message_iter_open_container().  Once this returns, the message
+ * is hosed and you have to start over building the whole message.
+ *
+ * This should only be used to abandon creation of a message when you have
+ * open containers.
+ *
+ * @param iter the append iterator
+ * @param sub sub-iterator to close
+ */
+void
+dbus_message_iter_abandon_container (DBusMessageIter *iter,
+                                     DBusMessageIter *sub)
+{
+  DBusMessageRealIter *real = (DBusMessageRealIter *)iter;
+  DBusMessageRealIter *real_sub = (DBusMessageRealIter *)sub;
+
+  _dbus_return_if_fail (_dbus_message_iter_append_check (real));
+  _dbus_return_if_fail (real->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
+  _dbus_return_if_fail (_dbus_message_iter_append_check (real_sub));
+  _dbus_return_if_fail (real_sub->iter_type == DBUS_MESSAGE_ITER_TYPE_WRITER);
+
+  _dbus_message_iter_abandon_signature (real);
+}
+
+/**
  * Sets a flag indicating that the message does not want a reply; if
  * this flag is set, the other end of the connection may (but is not
  * required to) optimize by not sending method return or error
@@ -2158,6 +2494,11 @@ dbus_message_iter_close_container (DBusMessageIter *iter,
  * message successfully arrived at the remote end. Normally you know a
  * message was received when you receive the reply to it.
  *
+ * The flag is #FALSE by default, that is by default the other end is
+ * required to reply.
+ *
+ * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_REPLY_EXPECTED
+ * 
  * @param message the message
  * @param no_reply #TRUE if no reply is desired
  */
@@ -2196,6 +2537,10 @@ dbus_message_get_no_reply (DBusMessage *message)
  * starting up, or fails to start up. In case of failure, the reply
  * will be an error.
  *
+ * The flag is set to #TRUE by default, i.e. auto starting is the default.
+ *
+ * On the protocol level this toggles #DBUS_HEADER_FLAG_NO_AUTO_START
+ * 
  * @param message the message
  * @param auto_start #TRUE if auto-starting is desired
  */
@@ -2233,6 +2578,9 @@ dbus_message_get_auto_start (DBusMessage *message)
  * DBUS_MESSAGE_TYPE_METHOD_CALL) or the one a signal is being
  * emitted from (for DBUS_MESSAGE_TYPE_SIGNAL).
  *
+ * The path must contain only valid characters as defined
+ * in the D-Bus specification.
+ *
  * @param message the message
  * @param object_path the path or #NULL to unset
  * @returns #FALSE if not enough memory
@@ -2258,6 +2606,11 @@ dbus_message_set_path (DBusMessage   *message,
  * DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted from (for
  * DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
  *
+ * See also dbus_message_get_path_decomposed().
+ *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ * 
  * @param message the message
  * @returns the path (should not be freed) or #NULL
  */
@@ -2277,6 +2630,39 @@ dbus_message_get_path (DBusMessage   *message)
 }
 
 /**
+ * Checks if the message has a particular object path.  The object
+ * path is the destination object for a method call or the emitting
+ * object for a signal.
+ *
+ * @param message the message
+ * @param path the path name
+ * @returns #TRUE if there is a path field in the header
+ */
+dbus_bool_t
+dbus_message_has_path (DBusMessage   *message,
+                       const char    *path)
+{
+  const char *msg_path;
+  msg_path = dbus_message_get_path (message);
+  
+  if (msg_path == NULL)
+    {
+      if (path == NULL)
+        return TRUE;
+      else
+        return FALSE;
+    }
+
+  if (path == NULL)
+    return FALSE;
+   
+  if (strcmp (msg_path, path) == 0)
+    return TRUE;
+
+  return FALSE;
+}
+
+/**
  * Gets the object path this message is being sent to
  * (for DBUS_MESSAGE_TYPE_METHOD_CALL) or being emitted
  * from (for DBUS_MESSAGE_TYPE_SIGNAL) in a decomposed
@@ -2287,6 +2673,8 @@ dbus_message_get_path (DBusMessage   *message)
  * So the path "/foo/bar" becomes { "foo", "bar", NULL }
  * and the path "/" becomes { NULL }.
  *
+ * See also dbus_message_get_path().
+ * 
  * @todo this could be optimized by using the len from the message
  * instead of calling strlen() again
  *
@@ -2321,6 +2709,9 @@ dbus_message_get_path_decomposed (DBusMessage   *message,
  * the interface a signal is being emitted from
  * (for DBUS_MESSAGE_TYPE_SIGNAL).
  *
+ * The interface name must contain only valid characters as defined
+ * in the D-Bus specification.
+ * 
  * @param message the message
  * @param interface the interface or #NULL to unset
  * @returns #FALSE if not enough memory
@@ -2348,6 +2739,9 @@ dbus_message_set_interface (DBusMessage  *message,
  * The interface name is fully-qualified (namespaced).
  * Returns #NULL if none.
  *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ *
  * @param message the message
  * @returns the message interface (should not be freed) or #NULL
  */
@@ -2367,10 +2761,44 @@ dbus_message_get_interface (DBusMessage *message)
 }
 
 /**
+ * Checks if the message has an interface
+ *
+ * @param message the message
+ * @param interface the interface name
+ * @returns #TRUE if the interface field in the header matches
+ */
+dbus_bool_t
+dbus_message_has_interface (DBusMessage   *message,
+                            const char    *interface)
+{
+  const char *msg_interface;
+  msg_interface = dbus_message_get_interface (message);
+   
+  if (msg_interface == NULL)
+    {
+      if (interface == NULL)
+        return TRUE;
+      else
+        return FALSE;
+    }
+
+  if (interface == NULL)
+    return FALSE;
+     
+  if (strcmp (msg_interface, interface) == 0)
+    return TRUE;
+
+  return FALSE;
+
+}
+
+/**
  * Sets the interface member being invoked
  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
  * (DBUS_MESSAGE_TYPE_SIGNAL).
- * The interface name is fully-qualified (namespaced).
+ *
+ * The member name must contain only valid characters as defined
+ * in the D-Bus specification.
  *
  * @param message the message
  * @param member the member or #NULL to unset
@@ -2397,6 +2825,9 @@ dbus_message_set_member (DBusMessage  *message,
  * (DBUS_MESSAGE_TYPE_METHOD_CALL) or emitted
  * (DBUS_MESSAGE_TYPE_SIGNAL). Returns #NULL if none.
  *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ * 
  * @param message the message
  * @returns the member name (should not be freed) or #NULL
  */
@@ -2416,9 +2847,44 @@ dbus_message_get_member (DBusMessage *message)
 }
 
 /**
+ * Checks if the message has an interface member
+ *
+ * @param message the message
+ * @param member the member name
+ * @returns #TRUE if there is a member field in the header
+ */
+dbus_bool_t
+dbus_message_has_member (DBusMessage   *message,
+                         const char    *member)
+{
+  const char *msg_member;
+  msg_member = dbus_message_get_member (message);
+  if (msg_member == NULL)
+    {
+      if (member == NULL)
+        return TRUE;
+      else
+        return FALSE;
+    }
+
+  if (member == NULL)
+    return FALSE;
+    
+  if (strcmp (msg_member, member) == 0)
+    return TRUE;
+
+  return FALSE;
+
+}
+
+/**
  * Sets the name of the error (DBUS_MESSAGE_TYPE_ERROR).
  * The name is fully-qualified (namespaced).
  *
+ * The error name must contain only valid characters as defined
+ * in the D-Bus specification.
+ *
  * @param message the message
  * @param error_name the name or #NULL to unset
  * @returns #FALSE if not enough memory
@@ -2443,6 +2909,9 @@ dbus_message_set_error_name (DBusMessage  *message,
  * Gets the error name (DBUS_MESSAGE_TYPE_ERROR only)
  * or #NULL if none.
  *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ * 
  * @param message the message
  * @returns the error name (should not be freed) or #NULL
  */
@@ -2467,6 +2936,9 @@ dbus_message_get_error_name (DBusMessage *message)
  * assigned by the bus to each connection, or a well-known name
  * specified in advance.
  *
+ * The destination name must contain only valid characters as defined
+ * in the D-Bus specification.
+ * 
  * @param message the message
  * @param destination the destination name or #NULL to unset
  * @returns #FALSE if not enough memory
@@ -2490,6 +2962,9 @@ dbus_message_set_destination (DBusMessage  *message,
 /**
  * Gets the destination of a message or #NULL if there is none set.
  *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ *
  * @param message the message
  * @returns the message destination (should not be freed) or #NULL
  */
@@ -2511,6 +2986,13 @@ dbus_message_get_destination (DBusMessage *message)
 /**
  * Sets the message sender.
  *
+ * The sender must be a valid bus name as defined in the D-Bus
+ * specification.
+ *
+ * Usually you don't want to call this. The message bus daemon will
+ * call it to set the origin of each message. If you aren't implementing
+ * a message bus daemon you shouldn't need to set the sender.
+ *
  * @param message the message
  * @param sender the sender or #NULL to unset
  * @returns #FALSE if not enough memory
@@ -2536,6 +3018,13 @@ dbus_message_set_sender (DBusMessage  *message,
  * message, or #NULL if unknown or inapplicable. The sender is filled
  * in by the message bus.
  *
+ * Note, the returned sender is always the unique bus name.
+ * Connections may own multiple other bus names, but those
+ * are not found in the sender field.
+ * 
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ *
  * @param message the message
  * @returns the unique name of the sender or #NULL
  */
@@ -2559,13 +3048,16 @@ dbus_message_get_sender (DBusMessage *message)
  * message payload. The signature includes only "in" arguments for
  * #DBUS_MESSAGE_TYPE_METHOD_CALL and only "out" arguments for
  * #DBUS_MESSAGE_TYPE_METHOD_RETURN, so is slightly different from
- * what you might expect (it does not include the signature of the
+ * what you might expect (that is, it does not include the signature of the
  * entire C++-style method).
  *
  * The signature is a string made up of type codes such as
  * #DBUS_TYPE_INT32. The string is terminated with nul (nul is also
  * the value of #DBUS_TYPE_INVALID).
  *
+ * The returned string becomes invalid if the message is
+ * modified, since it points into the wire-marshaled message data.
+ *
  * @param message the message
  * @returns the type signature
  */
@@ -2619,7 +3111,7 @@ _dbus_message_has_type_interface_member (DBusMessage *message,
  * interface and member fields.  If the message is not
  * #DBUS_MESSAGE_TYPE_METHOD_CALL, or has a different interface or
  * member field, returns #FALSE. If the interface field is missing,
- * then it will be assumed equal to the provided interface.  The D-BUS
+ * then it will be assumed equal to the provided interface.  The D-Bus
  * protocol allows method callers to leave out the interface name.
  *
  * @param message the message
@@ -2648,9 +3140,7 @@ dbus_message_is_method_call (DBusMessage *message,
 /**
  * Checks whether the message is a signal with the given interface and
  * member fields.  If the message is not #DBUS_MESSAGE_TYPE_SIGNAL, or
- * has a different interface or member field, returns #FALSE.  If the
- * interface field in the message is missing, it is assumed to match
- * any interface you pass in to this function.
+ * has a different interface or member field, returns #FALSE.
  *
  * @param message the message
  * @param interface the name to check (must not be #NULL)
@@ -2745,7 +3235,7 @@ dbus_message_has_destination (DBusMessage  *message,
  * unique name of the connection as the sender. So you can't use this
  * function to see whether a sender owned a well-known name.
  *
- * Messages from the bus itself will have #DBUS_SERVICE_ORG_FREEDESKTOP_DBUS
+ * Messages from the bus itself will have #DBUS_SERVICE_DBUS
  * as the sender.
  *
  * @param message the message
@@ -2805,7 +3295,7 @@ dbus_message_has_signature (DBusMessage   *message,
 /**
  * Sets a #DBusError based on the contents of the given
  * message. The error is only set if the message
- * is an error message, as in DBUS_MESSAGE_TYPE_ERROR.
+ * is an error message, as in #DBUS_MESSAGE_TYPE_ERROR.
  * The name of the error is set to the name of the message,
  * and the error message is set to the first argument
  * if the argument exists and is a string.
@@ -2822,7 +3312,7 @@ dbus_message_has_signature (DBusMessage   *message,
  *
  * @param error the error to set
  * @param message the message to set it from
- * @returns #TRUE if dbus_message_get_is_error() returns #TRUE for the message
+ * @returns #TRUE if the message had type #DBUS_MESSAGE_TYPE_ERROR
  */
 dbus_bool_t
 dbus_set_error_from_message (DBusError   *error,
@@ -2881,13 +3371,14 @@ _dbus_message_loader_new (void)
   loader = dbus_new0 (DBusMessageLoader, 1);
   if (loader == NULL)
     return NULL;
-
+  
   loader->refcount = 1;
 
-  /* Try to cap message size at something that won't *totally* hose
-   * the system if we have a couple of them.
-   */
-  loader->max_message_size = _DBUS_ONE_MEGABYTE * 32;
+  loader->corrupted = FALSE;
+  loader->corruption_reason = DBUS_VALID;
+
+  /* this can be configured by the app, but defaults to the protocol max */
+  loader->max_message_size = DBUS_MAXIMUM_MESSAGE_LENGTH;
 
   if (!_dbus_string_init (&loader->data))
     {
@@ -2967,13 +3458,6 @@ _dbus_message_loader_get_buffer (DBusMessageLoader  *loader,
 }
 
 /**
- * The smallest header size that can occur.  (It won't be valid due to
- * missing required header fields.) This is 4 bytes, two uint32, an
- * array length.
- */
-#define DBUS_MINIMUM_HEADER_SIZE 16
-
-/**
  * Returns a buffer obtained from _dbus_message_loader_get_buffer(),
  * indicating to the loader how many bytes of the buffer were filled
  * in. This function must always be called, even if no bytes were
@@ -3018,7 +3502,7 @@ _dbus_message_loader_return_buffer (DBusMessageLoader  *loader,
  * loader->data and only delete it occasionally, instead of after
  * each message is loaded.
  *
- * load_message() returns FALSE if not enough memory
+ * load_message() returns FALSE if not enough memory OR the loader was corrupted
  */
 static dbus_bool_t
 load_message (DBusMessageLoader *loader,
@@ -3032,7 +3516,10 @@ load_message (DBusMessageLoader *loader,
   DBusValidity validity;
   const DBusString *type_str;
   int type_pos;
+  DBusValidationMode mode;
 
+  mode = DBUS_VALIDATION_MODE_DATA_IS_UNTRUSTED;
+  
   oom = FALSE;
 
 #if 0
@@ -3043,18 +3530,29 @@ load_message (DBusMessageLoader *loader,
   _dbus_assert (_dbus_string_get_length (&message->header.data) == 0);
   _dbus_assert ((header_len + body_len) <= _dbus_string_get_length (&loader->data));
 
-  if (!_dbus_header_load_untrusted (&message->header,
-                                    &validity,
-                                    byte_order,
-                                    fields_array_len,
-                                    header_len,
-                                    body_len,
-                                    &loader->data, 0,
-                                    _dbus_string_get_length (&loader->data)))
+  if (!_dbus_header_load (&message->header,
+                          mode,
+                          &validity,
+                          byte_order,
+                          fields_array_len,
+                          header_len,
+                          body_len,
+                          &loader->data, 0,
+                          _dbus_string_get_length (&loader->data)))
     {
       _dbus_verbose ("Failed to load header for new message code %d\n", validity);
-      if (validity == DBUS_VALID)
+
+      /* assert here so we can catch any code that still uses DBUS_VALID to indicate
+         oom errors.  They should use DBUS_VALIDITY_UNKNOWN_OOM_ERROR instead */
+      _dbus_assert (validity != DBUS_VALID);
+
+      if (validity == DBUS_VALIDITY_UNKNOWN_OOM_ERROR)
         oom = TRUE;
+      else
+        {
+          loader->corrupted = TRUE;
+          loader->corruption_reason = validity;
+        }
       goto failed;
     }
 
@@ -3063,23 +3561,29 @@ load_message (DBusMessageLoader *loader,
   message->byte_order = byte_order;
 
   /* 2. VALIDATE BODY */
-
-  get_const_signature (&message->header, &type_str, &type_pos);
-
-  /* Because the bytes_remaining arg is NULL, this validates that the
-   * body is the right length
-   */
-  validity = _dbus_validate_body_with_reason (type_str,
-                                              type_pos,
-                                              byte_order,
-                                              NULL,
-                                              &loader->data,
-                                              header_len,
-                                              body_len);
-  if (validity != DBUS_VALID)
+  if (mode != DBUS_VALIDATION_MODE_WE_TRUST_THIS_DATA_ABSOLUTELY)
     {
-      _dbus_verbose ("Failed to validate message body code %d\n", validity);
-      goto failed;
+      get_const_signature (&message->header, &type_str, &type_pos);
+      
+      /* Because the bytes_remaining arg is NULL, this validates that the
+       * body is the right length
+       */
+      validity = _dbus_validate_body_with_reason (type_str,
+                                                  type_pos,
+                                                  byte_order,
+                                                  NULL,
+                                                  &loader->data,
+                                                  header_len,
+                                                  body_len);
+      if (validity != DBUS_VALID)
+        {
+          _dbus_verbose ("Failed to validate message body code %d\n", validity);
+
+          loader->corrupted = TRUE;
+          loader->corruption_reason = validity;
+          
+          goto failed;
+        }
     }
 
   /* 3. COPY OVER BODY AND QUEUE MESSAGE */
@@ -3104,6 +3608,9 @@ load_message (DBusMessageLoader *loader,
 
   _dbus_string_delete (&loader->data, 0, header_len + body_len);
 
+  /* don't waste more than 2k of memory */
+  _dbus_string_compact (&loader->data, 2048);
+
   _dbus_assert (_dbus_string_get_length (&message->header.data) == header_len);
   _dbus_assert (_dbus_string_get_length (&message->body) == body_len);
 
@@ -3111,6 +3618,8 @@ load_message (DBusMessageLoader *loader,
 
   _dbus_assert (!oom);
   _dbus_assert (!loader->corrupted);
+  _dbus_assert (loader->messages != NULL);
+  _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
 
   return TRUE;
 
@@ -3120,13 +3629,15 @@ load_message (DBusMessageLoader *loader,
 
   /* does nothing if the message isn't in the list */
   _dbus_list_remove_last (&loader->messages, message);
-
-  if (!oom)
-    loader->corrupted = TRUE;
+  
+  if (oom)
+    _dbus_assert (!loader->corrupted);
+  else
+    _dbus_assert (loader->corrupted);
 
   _dbus_verbose_bytes_of_string (&loader->data, 0, _dbus_string_get_length (&loader->data));
 
-  return !oom;
+  return FALSE;
 }
 
 /**
@@ -3174,15 +3685,24 @@ _dbus_message_loader_queue_messages (DBusMessageLoader *loader)
                              header_len, body_len))
             {
               dbus_message_unref (message);
-              return FALSE;
+              /* load_message() returns false if corrupted or OOM; if
+               * corrupted then return TRUE for not OOM
+               */
+              return loader->corrupted;
             }
+
+          _dbus_assert (loader->messages != NULL);
+          _dbus_assert (_dbus_list_find_last (&loader->messages, message) != NULL);
        }
       else
         {
           _dbus_verbose ("Initial peek at header says we don't have a whole message yet, or data broken with invalid code %d\n",
                          validity);
           if (validity != DBUS_VALID)
-            loader->corrupted = TRUE;
+            {
+              loader->corrupted = TRUE;
+              loader->corruption_reason = validity;
+            }
           return TRUE;
         }
     }
@@ -3259,10 +3779,27 @@ _dbus_message_loader_putback_message_link (DBusMessageLoader  *loader,
 dbus_bool_t
 _dbus_message_loader_get_is_corrupted (DBusMessageLoader *loader)
 {
+  _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
+                (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
   return loader->corrupted;
 }
 
 /**
+ * Checks what kind of bad data confused the loader.
+ *
+ * @param loader the loader
+ * @returns why the loader is hosed, or DBUS_VALID if it isn't.
+ */
+DBusValidity
+_dbus_message_loader_get_corruption_reason (DBusMessageLoader *loader)
+{
+  _dbus_assert ((loader->corrupted && loader->corruption_reason != DBUS_VALID) ||
+                (!loader->corrupted && loader->corruption_reason == DBUS_VALID));
+
+  return loader->corruption_reason;
+}
+
+/**
  * Sets the maximum size message we allow.
  *
  * @param loader the loader
@@ -3314,7 +3851,7 @@ dbus_bool_t
 dbus_message_allocate_data_slot (dbus_int32_t *slot_p)
 {
   return _dbus_data_slot_allocator_alloc (&slot_allocator,
-                                          _DBUS_LOCK_NAME (message_slots),
+                                          &_DBUS_LOCK_NAME (message_slots),
                                           slot_p);
 }
 
@@ -3403,7 +3940,7 @@ dbus_message_get_data (DBusMessage   *message,
 
 /**
  * Utility function to convert a machine-readable (not translated)
- * string into a D-BUS message type.
+ * string into a D-Bus message type.
  *
  * @code
  *   "method_call"    -> DBUS_MESSAGE_TYPE_METHOD_CALL
@@ -3430,7 +3967,7 @@ dbus_message_type_from_string (const char *type_str)
 }
 
 /**
- * Utility function to convert a D-BUS message type into a
+ * Utility function to convert a D-Bus message type into a
  * machine-readable string (not translated).
  *
  * @code
@@ -3460,6 +3997,177 @@ dbus_message_type_to_string (int type)
     }
 }
 
+/**
+ * Turn a DBusMessage into the marshalled form as described in the D-Bus
+ * specification.
+ *
+ * Generally, this function is only useful for encapsulating D-Bus messages in
+ * a different protocol.
+ *
+ * @param msg the DBusMessage
+ * @param marshalled_data_p the location to save the marshalled form to
+ * @param len_p the location to save the length of the marshalled form to
+ * @returns #FALSE if there was not enough memory
+ */
+dbus_bool_t
+dbus_message_marshal (DBusMessage  *msg,
+                      char        **marshalled_data_p,
+                      int          *len_p)
+{
+  DBusString tmp;
+  dbus_bool_t was_locked;
+
+  _dbus_return_val_if_fail (msg != NULL, FALSE);
+  _dbus_return_val_if_fail (marshalled_data_p != NULL, FALSE);
+  _dbus_return_val_if_fail (len_p != NULL, FALSE);
+  
+  if (!_dbus_string_init (&tmp))
+    return FALSE;
+
+  /* Ensure the message is locked, to ensure the length header is filled in. */
+  was_locked = msg->locked;
+
+  if (!was_locked)
+    dbus_message_lock (msg);
+
+  if (!_dbus_string_copy (&(msg->header.data), 0, &tmp, 0))
+    goto fail;
+
+  *len_p = _dbus_string_get_length (&tmp);
+
+  if (!_dbus_string_copy (&(msg->body), 0, &tmp, *len_p))
+    goto fail;
+
+  *len_p = _dbus_string_get_length (&tmp);
+
+  if (!_dbus_string_steal_data (&tmp, marshalled_data_p))
+    goto fail;
+
+  _dbus_string_free (&tmp);
+
+  if (!was_locked)
+    msg->locked = FALSE;
+
+  return TRUE;
+
+ fail:
+  _dbus_string_free (&tmp);
+
+  if (!was_locked)
+    msg->locked = FALSE;
+
+  return FALSE;
+}
+
+/**
+ * Demarshal a D-Bus message from the format described in the D-Bus
+ * specification.
+ *
+ * Generally, this function is only useful for encapsulating D-Bus messages in
+ * a different protocol.
+ *
+ * @param str the marshalled DBusMessage
+ * @param len the length of str
+ * @param error the location to save errors to
+ * @returns #NULL if there was an error
+ */
+DBusMessage *
+dbus_message_demarshal (const char *str,
+                        int         len,
+                        DBusError  *error)
+{
+  DBusMessageLoader *loader;
+  DBusString *buffer;
+  DBusMessage *msg;
+
+  _dbus_return_val_if_fail (str != NULL, NULL);
+
+  loader = _dbus_message_loader_new ();
+
+  if (loader == NULL)
+    return NULL;
+
+  _dbus_message_loader_get_buffer (loader, &buffer);
+  _dbus_string_append_len (buffer, str, len);
+  _dbus_message_loader_return_buffer (loader, buffer, len);
+
+  if (!_dbus_message_loader_queue_messages (loader))
+    goto fail_oom;
+
+  if (_dbus_message_loader_get_is_corrupted (loader))
+    goto fail_corrupt;
+
+  msg = _dbus_message_loader_pop_message (loader);
+
+  if (!msg)
+    goto fail_oom;
+
+  _dbus_message_loader_unref (loader);
+  return msg;
+
+ fail_corrupt:
+  dbus_set_error (error, DBUS_ERROR_INVALID_ARGS, "Message is corrupted (%s)",
+                  _dbus_validity_to_error_message (loader->corruption_reason));
+  _dbus_message_loader_unref (loader);
+  return NULL;
+
+ fail_oom:
+  _DBUS_SET_OOM (error);
+  _dbus_message_loader_unref (loader);
+  return NULL;
+}
+
+/**
+ * Returns the number of bytes required to be in the buffer to demarshal a
+ * D-Bus message.
+ *
+ * Generally, this function is only useful for encapsulating D-Bus messages in
+ * a different protocol.
+ *
+ * @param str data to be marshalled
+ * @param len the length of str
+ * @param error the location to save errors to
+ * @returns -1 if there was no valid data to be demarshalled, 0 if there wasn't enough data to determine how much should be demarshalled. Otherwise returns the number of bytes to be demarshalled
+ * 
+ */
+int 
+dbus_message_demarshal_bytes_needed(const char *buf, 
+                                    int         len)
+{
+  DBusString str;
+  int byte_order, fields_array_len, header_len, body_len;
+  DBusValidity validity = DBUS_VALID;
+  int have_message;
+
+  if (!buf || len < DBUS_MINIMUM_HEADER_SIZE)
+    return 0;
+
+  if (len > DBUS_MAXIMUM_MESSAGE_LENGTH)
+    len = DBUS_MAXIMUM_MESSAGE_LENGTH;
+  _dbus_string_init_const_len (&str, buf, len);
+  
+  validity = DBUS_VALID;
+  have_message
+    = _dbus_header_have_message_untrusted(DBUS_MAXIMUM_MESSAGE_LENGTH,
+                                          &validity, &byte_order,
+                                          &fields_array_len,
+                                          &header_len,
+                                          &body_len,
+                                          &str, 0,
+                                          len);
+  _dbus_string_free (&str);
+
+  if (validity == DBUS_VALID)
+    {
+      _dbus_assert(have_message);
+      return header_len + body_len;
+    }
+  else
+    {
+      return -1; /* broken! */
+    }
+}
+
 /** @} */
 
 /* tests in dbus-message-util.c */