Use correct format specifier

Use correct format specifier

--- examples/discovery/server_multicast.c
+++ examples/discovery/server_multicast.c
@@ -121,7 +121,7 @@
         return NULL;
     }

-    UA_LOG_DEBUG(logger, UA_LOGCATEGORY_SERVER, "Server has %ld endpoints", endpointArraySize);
+    UA_LOG_DEBUG(logger, UA_LOGCATEGORY_SERVER, "Server has %zu endpoints", endpointArraySize);
     UA_EndpointDescription *foundEndpoint = NULL;
     for (size_t i = 0; i < endpointArraySize; i++) {
         UA_LOG_DEBUG(logger, UA_LOGCATEGORY_SERVER, "\tURL = %.*s, SecurityMode = %s",


+ Added bilinear interpolation

+ Added bilinear interpolation

--- ionScience/Interpolation.h
+++ ionScience/Interpolation.h
@@ -2,19 +2,34 @@
 #pragma once

 template <typename T>
-T LinearInterpolate(T y1, T y2, float x)
+T LinearInterpolate(T y1, T y2, T x)
 {
 	return y1*(1 - x) + y2*x;
 }

 template <typename T>
-T CubicInterpolate(T p[4], float x)
+T LinearInterpolate(T p[2], T x)
+{
+	return p[0]*(1 - x) + p[1]*x;
+}
+
+template <typename T>
+T BilinearInterpolate(T p[2][2], T x, T y)
+{
+	T arr[2];
+	arr[0] = LinearInterpolate(p[0], y);
+	arr[1] = LinearInterpolate(p[1], y);
+	return LinearInterpolate(arr, x);
+}
+
+template <typename T>
+T CubicInterpolate(T p[4], T x)
 {
 	return p[1] + (T) 0.5 * x*(p[2] - p[0] + x*(2*p[0] - 5*p[1] + 4*p[2] - p[3] + x*(3*(p[1] - p[2]) + p[3] - p[0])));
 }

 template <typename T>
-T BicubicInterpolate(T p[4][4], float x, float y)
+T BicubicInterpolate(T p[4][4], T x, T y)
 {
 	T arr[4];
 	arr[0] = CubicInterpolate(p[0], y);
@@ -25,7 +40,7 @@
 }

 template <typename T>
-T TricubicInterpolate(T p[4][4][4], float x, float y, float z)
+T TricubicInterpolate(T p[4][4][4], T x, T y, T z)
 {
 	T arr[4];
 	arr[0] = BicubicInterpolate(p[0], y, z);


Built-ins set the ulValueLen to -1 to indicate an unknown attribute type.

--- security/nss/lib/dev/ckhelper.c
+++ security/nss/lib/dev/ckhelper.c
@@ -138,6 +138,10 @@
 	for (i=0; i<count; i++) {
 	    CK_ULONG ulValueLen = obj_template[i].ulValueLen;
 	    if (ulValueLen == 0) continue;
+	    if (ulValueLen < 0) {
+		obj_template[i].ulValueLen = 0;
+		continue;
+	    }
 	    if (is_string_attribute(obj_template[i].type)) {
 		ulValueLen++;
 	    }


Servo test: fix style

Servo test: fix style

--- src/systemcmds/tests/test_servo.c
+++ src/systemcmds/tests/test_servo.c
@@ -116,8 +116,10 @@
 	printf("Advancing channel 1 to 1800\n");
 	result = ioctl(fd, PWM_SERVO_SET(1), 1800);
 out:
+
 	if (fd >= 0) {
 		close(fd);
 	}
+
 	return 0;
 }


More cleanup for fdatasync hack

More cleanup for fdatasync hack

--- libraries/liblmdb/mdb.c
+++ libraries/liblmdb/mdb.c
@@ -81,7 +81,9 @@

 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
 /** fdatasync is broken on ext3/ext4fs on older kernels, see
- *	description in #mdb_env_open2 comments
+ *	description in #mdb_env_open2 comments. You can safely
+ *	define MDB_FDATASYNC_WORKS if this code will only be run
+ *	on kernels 3.6 and newer.
  */
 #define	BROKEN_FDATASYNC
 #endif
@@ -1144,6 +1146,8 @@
 #define	MDB_ENV_ACTIVE	0x20000000U
 	/** me_txkey is set */
 #define	MDB_ENV_TXKEY	0x10000000U
+	/** fdatasync is unreliable */
+#define	MDB_FSYNCONLY	0x08000000U
 	uint32_t 	me_flags;		/**< @ref mdb_env */
 	unsigned int	me_psize;	/**< DB page size, inited from me_os_psize */
 	unsigned int	me_os_psize;	/**< OS page size, from #GET_PAGESIZE */
@@ -1186,9 +1190,6 @@
 #ifdef _WIN32
 	int		me_pidquery;		/**< Used in OpenProcess */
 #endif
-#ifdef BROKEN_FDATASYNC
-	int		me_fsynconly;		/**< fdatasync is unreliable */
-#endif
 #if defined(_WIN32) || defined(MDB_USE_SYSV_SEM)
 	/* Windows mutexes/SysV semaphores do not reside in shared mem */
 	mdb_mutex_t	me_rmutex;
@@ -2368,7 +2369,7 @@
 #endif
 		} else {
 #ifdef BROKEN_FDATASYNC
-			if (env->me_fsynconly) {
+			if (env->me_flags & MDB_FSYNCONLY) {
 				if (fsync(env->me_fd))
 					rc = ErrCode();
 			} else
@@ -4000,7 +4001,7 @@
 			} else {	/* 4.x and newer is OK */
 				break;
 			}
-			env->me_fsynconly = 1;
+			env->me_flags |= MDB_FSYNCONLY;
 			break;
 		}
 	}


fixed am

fixed am

--- ir/be/ia32/ia32_optimize.c
+++ ir/be/ia32/ia32_optimize.c
@@ -1522,6 +1522,8 @@
 					DBG_OPT_AM_D(load, store, irn);

 					DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
+
+					need_exchange_on_fail = 0;
 				}
 			} /* if (store) */
 			else if (get_ia32_am_support(irn) & ia32_am_Source) {
@@ -1535,7 +1537,7 @@
 		}

 		/* was exchanged but optimize failed: exchange back */
-		if (check_am_src && need_exchange_on_fail) {
+		if (need_exchange_on_fail) {
 			exchange_left_right(irn, &left, &right, 3, 2);
 			cand = orig_cand;
 		}


Include TimeSeriesTable.h and add accessors for various special tables that return properly typed Tables

--- OpenSim/Common/XsensDataReader.h
+++ OpenSim/Common/XsensDataReader.h
@@ -27,6 +27,7 @@
 #include "ExperimentalSensor.h"
 #include "DataAdapter.h"
 #include "XsensDataReaderSettings.h"
+#include "TimeSeriesTable.h"
 /** @file
 * This file defines class for reading data files from IMU maker Xsens and
 * producing in memory tables to be consumed by the OpenSim tools/pipelines
@@ -69,7 +70,7 @@
     - one for AngularVelocity data.
     */
     DataAdapter::OutputTables extendRead(const std::string& folderName) const override;
-    /** Implements writing functionality.                                     */
+    /** Implements writing functionality, not implemented.                         */
     virtual void extendWrite(const DataAdapter::InputTables& tables,
         const std::string& sinkName) const override {};
     /**
@@ -86,6 +87,25 @@
     XsensDataReaderSettings& updSettings() {
         return _settings;
     }
+    /**
+     * Custom accessors to retrieve tables of proper types without need to casting by clients.
+     * Scripting friendly */
+    /** get table of Orientations as TimeSeriesTableQuaternion */
+    static const TimeSeriesTableQuaternion& getOrientationsTable(const DataAdapter::OutputTables& tables) {
+        return dynamic_cast<const TimeSeriesTableQuaternion&>(*tables.at(XsensDataReader::Orientations));
+    }
+    /** get table of LinearAccelerations as TimeSeriesTableVec3 */
+    static const TimeSeriesTableVec3& getLinearAccelerationsTable(const DataAdapter::OutputTables& tables) {
+        return dynamic_cast<const TimeSeriesTableVec3&>(*tables.at(XsensDataReader::LinearAccelerations));
+    }
+    /** get table of MagneticHeading as TimeSeriesTableVec3 */
+    static const TimeSeriesTableVec3& getMagneticHeadingTable(const DataAdapter::OutputTables& tables) {
+        return dynamic_cast<const TimeSeriesTableVec3&>(*tables.at(XsensDataReader::MagneticHeading));
+    }
+    /** get table of AngularVelocity as TimeSeriesTableVec3 */
+    static const TimeSeriesTableVec3& getAngularVelocityTable(const DataAdapter::OutputTables& tables) {
+        return dynamic_cast<const TimeSeriesTableVec3&>(*tables.at(XsensDataReader::AngularVelocity));
+    }
 private:
     /**
      * Find index of searchString in tokens


BugFix: variable was used before initialized

--- ir/be/ia32/ia32_optimize.c
+++ ir/be/ia32/ia32_optimize.c
@@ -475,6 +475,7 @@
 	/* ok, translate into Push */
 	edge       = get_irn_out_edge_first(irn);
 	old_proj_M = get_edge_src_irn(edge);
+	bl         = get_nodes_block(irn);

 	next = sched_next(irn);
 	sched_remove(irn);
@@ -496,7 +497,6 @@
 		mem   = new_r_Sync(irg, bl, 2, in);
 	}

-	bl   = get_nodes_block(irn);
 	push = new_rd_ia32_Push(NULL, irg, bl, be_get_IncSP_pred(sp), val, mem);
 	proj_res = new_r_Proj(irg, bl, push, get_irn_mode(sp), pn_ia32_Push_stack);
 	proj_M   = new_r_Proj(irg, bl, push, mode_M, pn_ia32_Push_M);


- Drop ValueVector usage here

- Drop ValueVector usage here

--- types/mapvalue.h
+++ types/mapvalue.h
@@ -47,7 +47,7 @@
 	}

 	bool operator()(Value* a, Value* b) const {
-		ValueVector vv(2);
+		std::vector<Value*> vv(2);
 		vv[0] = a;
 		vv[1] = b;


GPIO: Update gpio status before enable gpio irq.

If don't update gpio status, it will cause gpio IoTBus can't invoke upper level.
/*
  * gu_sample saved the old status for GPIO, it used when interrupt coming to compare
  * current status to gu_sample.
  * It update on system startup during gpio_register().
  * But, device driver init always after gpio init.
  * If GPIO status changed after gpio_register(), it will not record.
  * So, we update gu_sample before enable gpio irq.
*/

Change-Id: I3c158c721de33f1324d4aff8dd916dcbb08697a3
signed-off-by: kai lv <16881f9557d75ca0b4a7b62e460c49d15685a07f@samsung.com>

--- os/drivers/gpio/gpio.c
+++ os/drivers/gpio/gpio.c
@@ -270,6 +270,15 @@
 	/* Enable/disable GPIO interrupts */
 	DEBUGASSERT(lower->ops->enable);
 	if (rising || falling) {
+		/*
+		  * gu_sample saved the old status for GPIO, it used when interrupt coming to compare
+		  * current status to gu_sample.
+		  * It update on system startup during gpio_register().
+		  * But, device driver init always after gpio init.
+		  * If GPIO status changed after gpio_register(), it will not record.
+		  * So, we update gu_sample before enable gpio irq.
+		  */
+		priv->gu_sample = lower->ops->get(lower);
 		lower->ops->enable(lower, falling, rising, gpio_interrupt);
 	} else {
 		/* Disable further interrupts */


Update the current magic number, and add a constant for the length of an SHA-1 hash.

--- os/imagezip/imagehdr.h
+++ os/imagezip/imagehdr.h
@@ -26,7 +26,7 @@
 #define COMPRESSED_V3			(COMPRESSED_MAGIC_BASE+2)
 #define COMPRESSED_V4			(COMPRESSED_MAGIC_BASE+3)

-#define COMPRESSED_MAGIC_CURRENT	COMPRESSED_V3
+#define COMPRESSED_MAGIC_CURRENT	COMPRESSED_V4

 /*
  * Each compressed block of the file has this little header on it.
@@ -98,6 +98,11 @@
 #define CHECKSUM_SHA1   0

 /*
+ * Length of the checksum field (in bytes) for various checksum types
+ */
+#define CHECKSUM_LEN_SHA1 20
+
+/*
  * Ciphers supported
  */
 #define ENCRYPTION_NULL 0


(initerrors): Make sure that the exception tuples ("base-classes" when string-based exceptions are used) reflect the real class hierarchy, i.e. that SystemExit derives from Exception not StandardError.

--- Python/bltinmodule.c
+++ Python/bltinmodule.c
@@ -2153,7 +2153,7 @@
 initerrors(dict)
 	PyObject *dict;
 {
-	int i;
+	int i, j;
 	int exccnt = 0;
 	for (i = 0; bltin_exc[i].name; i++, exccnt++) {
 		Py_XDECREF(*bltin_exc[i].exc);
@@ -2190,22 +2190,32 @@
 	PyTuple_SET_ITEM(PyExc_EnvironmentError, 1, PyExc_OSError);
 	PyDict_SetItemString(dict, "EnvironmentError", PyExc_EnvironmentError);

-	PyExc_StandardError = PyTuple_New(exccnt-2);
-	for (i = 2; bltin_exc[i].name; i++) {
+	/* missing from the StandardError tuple: Exception, StandardError,
+	 * and SystemExit
+	 */
+	PyExc_StandardError = PyTuple_New(exccnt-3);
+	for (i = 2, j = 0; bltin_exc[i].name; i++) {
 		PyObject *exc = *bltin_exc[i].exc;
-		Py_INCREF(exc);
-		PyTuple_SET_ITEM(PyExc_StandardError, i-2, exc);
+		/* SystemExit is not an error, but it is an exception */
+		if (exc != PyExc_SystemExit) {
+			Py_INCREF(exc);
+			PyTuple_SET_ITEM(PyExc_StandardError, j++, exc);
+		}
 	}
 	PyDict_SetItemString(dict, "StandardError", PyExc_StandardError);

-	/* Exception is treated differently; for now, it's == StandardError */
-	PyExc_Exception = PyExc_StandardError;
-	Py_INCREF(PyExc_Exception);
+	/* Exception is a 2-tuple */
+	PyExc_Exception = PyTuple_New(2);
+	Py_INCREF(PyExc_SystemExit);
+	PyTuple_SET_ITEM(PyExc_Exception, 0, PyExc_SystemExit);
+	Py_INCREF(PyExc_StandardError);
+	PyTuple_SET_ITEM(PyExc_Exception, 1, PyExc_StandardError);
 	PyDict_SetItemString(dict, "Exception", PyExc_Exception);

 	if (PyErr_Occurred())
 	      Py_FatalError("Could not initialize built-in string exceptions");
 }
+

 static void
 finierrors()


ETCH-290 Removed Static mutex inside of EtchConnection

EtchConnections suffer to a Deadlock with multiple EtchSessions /
Connections. Removing the static mutex solves this issue.

Change-Id: If9c5ed101a247a33245a750467e64b1b37dda410

git-svn-id: 413dc58a15145b085e84d1a9a38cb4ab1fc93382@1579566 13f79535-47bb-0310-9956-ffa450edef68

--- binding-cpp/runtime/include/transport/EtchConnection.h
+++ binding-cpp/runtime/include/transport/EtchConnection.h
@@ -131,8 +131,8 @@
   capu::Thread *mThread;
   capu::bool_t mIsStarted;
   capu::bool_t mIsTerminated;
-  static capu::Mutex mMutex;
-  static capu::Mutex mMutexConnection;
+  capu::Mutex mMutex;
+  capu::Mutex mMutexConnection;
   EtchMonitor mStatus;
 };

@@ -144,12 +144,6 @@

 template <class S>
 const EtchString EtchConnection<S>::ALL_INTFS("0.0.0.0");
-
-template <class S>
-capu::Mutex EtchConnection<S>::mMutex;
-
-template <class S>
-capu::Mutex EtchConnection<S>::mMutexConnection;

 template <class S>
 EtchConnection<S>::EtchConnection()


ukvm: Formatting fixes in vcpu_loop()

ukvm: Formatting fixes in vcpu_loop()

No functional change. The final return statement in vcpu_loop() is
removed on purpose, the compiler is smart enough to tell that this code
will not be reached (and complain if someone changes the logic later).

--- ukvm/ukvm-core.c
+++ ukvm/ukvm-core.c
@@ -457,10 +457,10 @@
             continue;

         switch (run->exit_reason) {
-        case KVM_EXIT_HLT: {
+        case KVM_EXIT_HLT:
             /* Guest has halted the CPU, this is considered as a normal exit. */
             return 0;
-        }
+
         case KVM_EXIT_IO: {
             assert(run->io.direction == KVM_EXIT_IO_OUT);
             assert(run->io.size == 4);
@@ -476,21 +476,22 @@
                 break;
             default:
                 errx(1, "Invalid guest port access: port=0x%x", run->io.port);
-            };
+            }
             break;
         }
+
         case KVM_EXIT_FAIL_ENTRY:
             errx(1, "KVM: entry failure: hw_entry_failure_reason=0x%llx",
                  run->fail_entry.hardware_entry_failure_reason);
+
         case KVM_EXIT_INTERNAL_ERROR:
             errx(1, "KVM: internal error exit: suberror=0x%x",
                  run->internal.suberror);
+
         default:
             errx(1, "KVM: unhandled exit: exit_reason=0x%x", run->exit_reason);
         }
     }
-
-    return 0; /* XXX Refactor return code paths in the above code */
 }

 int setup_modules(int vcpufd, uint8_t *mem)


unit/test-gatt: Add TP/GAW/SR/BV-06-C test

Verify that a Generic Attribute Profile server can support reliable
writing to a Characteristic Value selected by handle.


changed to declared the closed state only after some count

--- catdoor_v2/libs/lis3dh/src/accel.h
+++ catdoor_v2/libs/lis3dh/src/accel.h
@@ -16,6 +16,7 @@
   static const int16_t V_OPENED = -13000;
   static const int16_t H_OPENED = 10000;
   static const uint8_t JAMCOUNTS = 10;  // 1.2s at 10Hz
+  static const uint8_t CLOSED_COUNTS = 4;
   // Horizontal:
   // Zaccel > 0 --> open IN
   // Zaccel < 0 --> open OUT
@@ -29,19 +30,22 @@
   volatile bool data_ready;
   volatile bool new_state;
   volatile state_t state;
-  uint8_t jamcounter;
+  uint8_t jamcounter;      // "integrate" time jammed is detected
+  uint8_t closed_counter;  // just count number of successive closed

   Accel(void)
       : ADA_LIS3DH(),
         data_ready(false),
         new_state(false),
         state(CLOSED),
-        jamcounter(0) {}
+        jamcounter(0),
+        closed_counter(0) {}

   void change_state(state_t s) {
     state = s;
     new_state = true;
     jamcounter = 0;
+    closed_counter = 0;
   }

   void process() {
@@ -55,7 +59,10 @@
     // compute new state
     if (accel[0] < V_CLOSED && abs(accel[2]) < H_CLOSED) {
       if (state != CLOSED) {
-        change_state(CLOSED);
+        closed_counter++;
+        if (closed_counter > CLOSED_COUNTS) {
+          change_state(CLOSED);
+        }
       }
       if (jamcounter > 0) jamcounter--;
       return;


SceneGraph: remove forward declaration for deprecated enum.

There was no point in using it anywhere else than when passing it to the
transformation function itself.

--- src/Magnum/SceneGraph/SceneGraph.h
+++ src/Magnum/SceneGraph/SceneGraph.h
@@ -63,10 +63,6 @@
 template<class T> using AbstractBasicObject3D = AbstractObject<3, T>;
 typedef AbstractBasicObject2D<Float> AbstractObject2D;
 typedef AbstractBasicObject3D<Float> AbstractObject3D;
-
-#ifdef MAGNUM_BUILD_DEPRECATED
-enum class TransformationType: UnsignedByte;
-#endif

 template<UnsignedInt, class> class AbstractTransformation;
 template<class T> using AbstractBasicTransformation2D = AbstractTransformation<2, T>;


Misc. source comment typo [skip ci]

Misc. source comment typo [skip ci]

Found via `codespell`
[skip ci]

--- src/Mod/Mesh/App/Core/MeshKernel.h
+++ src/Mod/Mesh/App/Core/MeshKernel.h
@@ -406,7 +406,7 @@
     void Smooth(int iterations, float d_max);
     /**
      * CheckFacets() is invoked within this method and all found facets get deleted from the mesh structure.
-     * The facets to be deleted are returned with their geometric reprsentation.
+     * The facets to be deleted are returned with their geometric representation.
      * @see CheckFacets().
      */
     void CutFacets (const MeshFacetGrid& rclGrid, const Base::ViewProjMethod *pclP, const Base::Polygon2d& rclPoly,


options: Fix a potential memory leak

options: Fix a potential memory leak

--- src/if-options.c
+++ src/if-options.c
@@ -1868,6 +1868,7 @@
 		    ifo->vivco_len + 1, sizeof(*ifo->vivco));
 		if (vivco == NULL) {
 			logerr( __func__);
+			fre(np);
 			return -1;
 		}
 		ifo->vivco = vivco;


Refactor determining whether to send chat states

--- src/im-channel.c
+++ src/im-channel.c
@@ -393,18 +393,26 @@
   tp_message_mixin_init_dbus_properties (object_class);
 }

-static void
-emit_closed_and_send_gone (GabbleIMChannel *self)
+static gboolean
+chat_states_supported (GabbleIMChannel *self)
 {
   GabbleIMChannelPrivate *priv = self->priv;
   GabblePresence *presence;

+  presence = gabble_presence_cache_get (priv->conn->presence_cache,
+      priv->handle);
+
+  return (presence != NULL && (presence->caps & PRESENCE_CAP_CHAT_STATES));
+}
+
+static void
+emit_closed_and_send_gone (GabbleIMChannel *self)
+{
+  GabbleIMChannelPrivate *priv = self->priv;
+
   if (priv->send_gone)
     {
-      presence = gabble_presence_cache_get (priv->conn->presence_cache,
-          priv->handle);
-
-      if (presence && (presence->caps & PRESENCE_CAP_CHAT_STATES))
+      if (chat_states_supported (self))
         gabble_message_util_send_chat_state (G_OBJECT (self), priv->conn,
             LM_MESSAGE_SUB_TYPE_NORMAL, TP_CHANNEL_CHAT_STATE_GONE,
             priv->peer_jid, NULL);
@@ -486,16 +494,12 @@
 {
   GabbleIMChannel *self = GABBLE_IM_CHANNEL (object);
   GabbleIMChannelPrivate *priv;
-  GabblePresence *presence;
   gint state = -1;

   g_assert (GABBLE_IS_IM_CHANNEL (self));
   priv = self->priv;

-  presence = gabble_presence_cache_get (priv->conn->presence_cache,
-      priv->handle);
-
-  if (presence && (presence->caps & PRESENCE_CAP_CHAT_STATES))
+  if (chat_states_supported (self))
     {
       state = TP_CHANNEL_CHAT_STATE_ACTIVE;
       priv->send_gone = TRUE;
@@ -789,53 +793,47 @@
 {
   GabbleIMChannel *self = GABBLE_IM_CHANNEL (iface);
   GabbleIMChannelPrivate *priv;
-  GabblePresence *presence;
   GError *error = NULL;

   g_assert (GABBLE_IS_IM_CHANNEL (self));
   priv = self->priv;

-  presence = gabble_presence_cache_get (priv->conn->presence_cache,
-      priv->handle);
-
-  if (presence && (presence->caps & PRESENCE_CAP_CHAT_STATES))
-    {
-      if (state >= NUM_TP_CHANNEL_CHAT_STATES)
-        {
-          DEBUG ("invalid state %u", state);
-
-          g_set_error (&error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
-              "invalid state: %u", state);
-        }
-
-      if (state == TP_CHANNEL_CHAT_STATE_GONE)
-        {
-          /* We cannot explicitly set the Gone state */
-          DEBUG ("you may not explicitly set the Gone state");
-
-          g_set_error (&error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
-              "you may not explicitly set the Gone state");
-        }
-      else if (gabble_message_util_send_chat_state (G_OBJECT (self), priv->conn,
-          LM_MESSAGE_SUB_TYPE_NORMAL, state, priv->peer_jid, &error))
+  if (state >= NUM_TP_CHANNEL_CHAT_STATES)
+    {
+      g_set_error (&error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
+          "invalid state: %u", state);
+    }
+  else if (state == TP_CHANNEL_CHAT_STATE_GONE)
+    {
+      g_set_error (&error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
+          "you may not explicitly set the Gone state");
+    }
+  /* Only send anything to the peer if we actually know they support chat
+   * states.
+   */
+  else if (chat_states_supported (self))
+    {
+      if (gabble_message_util_send_chat_state (G_OBJECT (self), priv->conn,
+              LM_MESSAGE_SUB_TYPE_NORMAL, state, priv->peer_jid, &error))
         {
           priv->send_gone = TRUE;
+
+          /* Send the ChatStateChanged signal for the local user */
+          tp_svc_channel_interface_chat_state_emit_chat_state_changed (iface,
+              priv->conn->parent.self_handle, state);
         }
-
-      if (error != NULL)
-        {
-          dbus_g_method_return_error (context, error);
-          g_error_free (error);
-
-          return;
-        }
-
-      /* Send the ChatStateChanged signal for the local user */
-      tp_svc_channel_interface_chat_state_emit_chat_state_changed (iface,
-          priv->conn->parent.self_handle, state);
-    }
-
-  tp_svc_channel_interface_chat_state_return_from_set_chat_state (context);
+    }
+
+  if (error != NULL)
+    {
+      DEBUG ("%s", error->message);
+      dbus_g_method_return_error (context, error);
+      g_error_free (error);
+    }
+  else
+    {
+      tp_svc_channel_interface_chat_state_return_from_set_chat_state (context);
+    }
 }

 static void


The Windows screen driver should set ScreenDescription.unreadable. (st)

git-svn-id: 30a5f035a20f1bc647618dbad7eea2a951b61b7c@1982 91a5dbb7-01b9-0310-9b5f-b28072856b6e

--- ScreenDrivers/Windows/screen.c
+++ ScreenDrivers/Windows/screen.c
@@ -107,8 +107,6 @@
   closeStdHandles();
 }

-static const char noterm [] = "no terminal to read";
-
 static int
 selectvt_WindowsScreen (int vt) {
   return 0;
@@ -128,12 +126,20 @@
 describe_WindowsScreen (ScreenDescription *description) {
   CONSOLE_SCREEN_BUFFER_INFO info;
   description->number = currentvt_WindowsScreen();
-  if (!tryToAttach()) goto error;
-  if (consoleOutput == INVALID_HANDLE_VALUE) goto error;
+  description->unreadable = NULL;
+  if (!tryToAttach()) {
+    description->unreadable = "no terminal to read";
+    goto error;
+  }
+  if (consoleOutput == INVALID_HANDLE_VALUE) {
+    description->unreadable = "can't open terminal output";
+    goto error;
+  }
   if (!(GetConsoleScreenBufferInfo(consoleOutput, &info))) {
     LogWindowsError("GetConsoleScreenBufferInfo");
     CloseHandle(consoleOutput);
     consoleOutput = INVALID_HANDLE_VALUE;
+    description->unreadable = "can't read terminal information";
     goto error;
   }
   description->cols = info.srWindow.Right + 1 - info.srWindow.Left;
@@ -144,7 +150,7 @@

 error:
   description->rows = 1;
-  description->cols = strlen(noterm);
+  description->cols = strlen(description->unreadable);
   description->posx = 0;
   description->posy = 0;
 }
@@ -155,14 +161,19 @@
   int text = mode == SCR_TEXT;
   int x, y;
   COORD coord;
+  ScreenDescription scr;

   BOOL WINAPI (*fun) (HANDLE, void*, DWORD, COORD, LPDWORD);
   const char *name;
   size_t size;
   void *buf;

-  if (!tryToAttach()) goto error;
-  if (consoleOutput == INVALID_HANDLE_VALUE) goto error;
+  describe_WindowsScreen(&scr);
+  if (scr.unreadable) {
+    setScreenMessage(&box, buffer, mode, scr.unreadable);
+    return 1;
+  }
+  if (!validateScreenBox(&box, scr.cols, scr.rows)) return 0;

   {
     CONSOLE_SCREEN_BUFFER_INFO info;
@@ -171,15 +182,11 @@
       LogWindowsError("GetConsoleScreenBufferInfo");
       CloseHandle(consoleOutput);
       consoleOutput = INVALID_HANDLE_VALUE;
-      goto error;
+      return 0;
     }

     coord.X = box.left + info.srWindow.Left;
     coord.Y = box.top + info.srWindow.Top;
-    if (!validateScreenBox(&box,
-                           info.srWindow.Right - info.srWindow.Left + 1,
-                           info.srWindow.Bottom - info.srWindow.Top + 1))
-      goto error;
   }

 #define USE(f, t) (fun = (typeof(fun))f, name = #f, size = sizeof(t))
@@ -201,8 +208,8 @@
 #endif /* HAVE_FUNC_READCONSOLEOUTPUTCHARACTERW */
   {
     if (!(buf = malloc(box.width*size))) {
-      LogError("malloc");
-      goto error;
+      LogError("malloc for Windows console reading");
+      return 0;
     }
   }

@@ -244,23 +251,7 @@
     free(buf);
   }

-  if (y == box.height) return 1;
-
-error:
-  {
-    int count = box.width * box.height;
-    if (text) {
-      int length = strlen(noterm) - box.left;
-      if (length < 0) length = 0;
-      if (length > count) length = count;
-      memset(buffer, ' ', count);
-      if (length > 0) memcpy(buffer, noterm+box.left, length);
-    } else {
-      memset(buffer, 0X07, count);
-    }
-  }
-
-  return 0;
+  return (y == box.height);
 }

 static int


Handle supplementary alignments.

Handle supplementary alignments.

--- src/indelminer.c
+++ src/indelminer.c
@@ -348,6 +348,7 @@
     if((alignment->core.flag & 0x100) == 0x100) return 0;
     if((alignment->core.flag & 0x200) == 0x200) return 0;
     if((alignment->core.flag & 0x400) == 0x400) return 0;
+    if((alignment->core.flag & 0x800) == 0x800) return 0;

     bool is_aligned = (alignment->core.flag & 0x4) == 0;
     bool is_mate_aligned = (alignment->core.flag & 0x8) == 0;


[cage] another PMC_x_val removal

[cage] another PMC_x_val removal

git-svn-id: 6e74a02f85675cec270f5d931b0f6998666294a3@35525 d31e2699-5ff4-0310-a27c-f18f2fbe73fe

--- src/inter_call.c
+++ src/inter_call.c
@@ -557,7 +557,7 @@

         /* create key needed to iterate the hash */
         st->key              = pmc_new(interp, enum_class_Key);
-        PMC_int_val(st->key) = 0;
+        key_set_integer(interp, st->key, 0);
         PMC_data(st->key)    = (void *)INITBucketIndex;
     }
     else {


Buffer overflow exploit with static address

* Exploit an unchecked strcpy to set the return pointer to an
  abritrary known address

Next step: shellcode!

error: pathspec 'shellcode/smash_ret_2.c' did not match any file(s) known to git

--- shellcode/smash_ret_2.c
+++ shellcode/smash_ret_2.c
@@ -0,0 +1,63 @@
+// gcc -mpreferred-stack-boundary=2 -ggdb smash_ret_2.c -o smash_ret_2
+// Smash a function return pointer with an argument buffer overflow
+#include <stdio.h>
+#include <string.h>
+
+void function(char* s, int n) {
+  char buf[4];
+  strcpy(buf, s);
+  printf("%s\n", buf);
+}
+
+int main(void) {
+  char s[] =
+    "\x31\x32\x33\x34"  // 3 expected bytes + splat expected NULL
+    "\x35\x36\x37\x38"  // splat $esp with anything
+    "\x73\x84\x04\x08"; // splat $ret with a real address
+
+  function(s, 0xf);
+  printf("back in main\n");
+}
+
+// Working out what arg to `function` is needed to overflow:
+
+// stack at line 8 when passing "123" (0xf) is a visual marker
+// to help find things in the stack
+//
+// (gdb) x/5xw $esp
+//
+// TOP
+// 0x00333231 // buf
+// 0xffffdd58 // $ebp
+// 0x0804845d // $ret
+// 0x08048500 // &s
+// 0x0000000f // n
+
+// With "1234567" s overflows by 4 bytes and overwrites $esp:
+// 0x34333231 // buf 1
+// 0x00373635 // buf 2 (splatted $ebp)
+// 0x0804845d // $ret
+// 0x08048500 // &s
+// 0x0000000f // n
+//
+// With "12345671234" s overflows by 8 bytes:
+// 0x34333231 // buf 1
+// 0x31373635 // buf 2 (splatted $ebp)
+// 0x00343332 // buf 3 (splatted $ret)
+// 0x08048500 // &s
+// 0x0000000f // n
+//
+// Good! ret is splatted bu the arg buffer. Now set it to a real
+// address from main with
+// s = "\x31\x32\x33\x34\x35\x36\x37\x38\x73\x84\x04\x08"
+//
+// 0x08048473 is the `call function` instruction. Reverse the bytes
+// because x86 is little endian
+//
+// 0x34333231 // buf 1
+// 0x8a363635 // buf 2 (splatted $ebp)
+// 0x00080484 // buf 3 (splatted $ret with a real address)
+// 0xffffdd4c // &s
+// 0x0000000f // n
+//
+// Success! function gets called twice! (then segfaults)


examples/l2fwd-crypto: check return value on IV size check

IV size parameter is checked through a function,
but its return value was not checked.

Fixes: 0fbd75a99fc9 ("cryptodev: move IV parameters to session")
Fixes: acf8616901b5 ("cryptodev: add auth IV")
Fixes: 2661f4fbe93d ("examples/l2fwd-crypto: add AEAD parameters")
Cc: stable@dpdk.org

Signed-off-by: Pablo de Lara <28355d9cfe41bb8148aea0fb24f47aae8f4217a1@intel.com>
Acked-by: Fiona Trahe <7ba562cc372916cd557d0be347608f8b4da4f746@intel.com>

--- examples/l2fwd-crypto/main.c
+++ examples/l2fwd-crypto/main.c
@@ -2066,10 +2066,11 @@

 			options->block_size = cap->sym.aead.block_size;

-			check_iv_param(&cap->sym.aead.iv_size,
+			if (check_iv_param(&cap->sym.aead.iv_size,
 					options->aead_iv_param,
 					options->aead_iv_random_size,
-					&options->aead_iv.length);
+					&options->aead_iv.length) < 0)
+				return -1;

 			/*
 			 * Check if length of provided AEAD key is supported
@@ -2174,10 +2175,11 @@

 			options->block_size = cap->sym.cipher.block_size;

-			check_iv_param(&cap->sym.cipher.iv_size,
+			if (check_iv_param(&cap->sym.cipher.iv_size,
 					options->cipher_iv_param,
 					options->cipher_iv_random_size,
-					&options->cipher_iv.length);
+					&options->cipher_iv.length) < 0)
+				return -1;

 			/*
 			 * Check if length of provided cipher key is supported
@@ -2230,10 +2232,11 @@
 			if (cap == NULL)
 				continue;

-			check_iv_param(&cap->sym.auth.iv_size,
+			if (check_iv_param(&cap->sym.auth.iv_size,
 					options->auth_iv_param,
 					options->auth_iv_random_size,
-					&options->auth_iv.length);
+					&options->auth_iv.length) < 0)
+				return -1;
 			/*
 			 * Check if length of provided auth key is supported
 			 * by the algorithm chosen.


oc_endpoint: fix condition for DNS lookup

Change-Id: I8ef97b41d4c93700084e91d50fc653a073589aa5
Signed-off-by: Kishen Maloor <c62ddea3cd661a9268bff15f07fc2229cdc9ac02@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/26039

--- api/oc_endpoint.c
+++ api/oc_endpoint.c
@@ -353,7 +353,8 @@
     oc_string_t ipaddress;
     memset(&ipaddress, 0, sizeof(oc_string_t));
 #endif /* OC_DNS_LOOKUP */
-    if ('A' <= address[address_len - 1] && 'z' >= address[address_len - 1]) {
+    if (('A' <= address[address_len - 1] && 'Z' >= address[address_len - 1]) ||
+        ('a' <= address[address_len - 1] && 'z' >= address[address_len - 1])) {
 #ifdef OC_DNS_LOOKUP
       char domain[address_len + 1];
       strncpy(domain, address, address_len);


git-svn-id: https://www.imagemagick.org/subversion/ImageMagick/trunk@8208 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74

--- MagickCore/attribute.c
+++ MagickCore/attribute.c
@@ -962,10 +962,6 @@
           image->colormap[i].alpha=(double) ScaleAnyToQuantum(ScaleQuantumToAny(
             ClampToQuantum(image->colormap[i].alpha),range),range);
       }
-      status=SyncImage(image,exception);
-      if (status != MagickFalse)
-        image->depth=depth;
-      return(status);
     }
   status=MagickTrue;
   image_view=AcquireAuthenticCacheView(image,exception);


Improve flag parsing.

Improve flag parsing.

--- lumberjack.c
+++ lumberjack.c
@@ -9,16 +9,27 @@
 #include "emitter.h"
 #include <jemalloc/jemalloc.h>
 #include <signal.h>
+#include <string.h>
+
+#define ZMQ_EMITTER_ENDPOINT "inproc://emitter"

 typedef enum {
   opt_help = 'h',
   opt_version = 'v',
   opt_field,
+  opt_ssl_ca_path,
 } optlist_t;

-static struct option options[] = {
-  { "help", no_argument, NULL, opt_help },
-  { "version", no_argument, NULL, opt_version },
+struct option_doc {
+  const char *name;
+  int         has_arg;
+  int         val;
+  const char *documentation;
+};
+
+static struct option_doc options[] = {
+  { "help", no_argument, opt_help, "show this help" },
+  { "version", no_argument, opt_version, "show the version of lumberjack" },

   /* Support arbitrary fields in the events, like:
    * ./lumberjack --field host=$(hostname) --field role=frontend .../access.log
@@ -26,16 +37,75 @@
    * This will allow you to send any arbitrary data along with every event.
    * { "host": "foo", "file": "/path/to/file.log", "message": "hello ..." }
    */
-  { "field", required_argument, NULL, opt_field },
-  { NULL, 0, NULL, 0 }
+  { "field", required_argument, opt_field,
+    "Add a custom key-value mapping to every line emitted" },
+
+  /* ssl cert and key, optional */
+  //{ "ssl-certificate", required_argument, NULL, opt_ssl_certificate },
+  //{ "ssl-key", required_argument, NULL, opt_ssl_key },
+  /* TODO(sissel): How to provide key passphrase/credentials? */
+
+  /* What cert authority to trust. This can be the path to a single self-signed
+   * certificate if you choose. */
+  { "ssl-ca-path", required_argument, opt_ssl_ca_path,
+    "Set the trusted cert/ca path for lumberjack's ssl client. " \
+    "Can be a file or a directory." },
+  { NULL, 0, 0, NULL },
 };

-#define ZMQ_EMITTER_ENDPOINT "inproc://emitter"
+void usage(const char *prog) {
+  printf("Usage: %s [options] /path/to/file [/path/to/file2 ...]\n", prog);
+
+  for (int i = 0; options[i].name != NULL; i++) {
+    printf("  --%s%s %.*s %s\n", options[i].name,
+           options[i].has_arg ? " VALUE" : "",
+           (int)(20 - strlen(options[i].name) - (options[i].has_arg ? 6 : 0)),
+           "                                   ",
+           options[i].documentation);
+  }
+} /* usage */

 int main(int argc, char **argv) {
   int c, i;
-  while (c = getopt_long_only(argc, argv, "+hv", options, &i), c != -1) {
+  struct emitter_config emitter_config;
+  struct option *getopt_options = NULL;
+
+  /* convert the 'option_doc' array into a 'struct option' array
+   * for use with getopt_long_only */
+  for (i = 0; options[i].name != NULL; i++) {
+    getopt_options = realloc(getopt_options, (i+1) * sizeof(struct option));
+    getopt_options[i].name = options[i].name;
+    getopt_options[i].has_arg = options[i].has_arg;
+    getopt_options[i].flag = NULL;
+    getopt_options[i].val = options[i].val;
+  }
+
+  /* Add one last item for the list terminator NULL */
+  getopt_options = realloc(getopt_options, (i+1) * sizeof(struct option));
+  getopt_options[i].name = NULL;
+
+  while (i = -1, c = getopt_long_only(argc, argv, "+hv", getopt_options, &i), c != -1) {
     /* TODO(sissel): handle args */
+    switch (c) {
+      case opt_ssl_ca_path:
+        emitter_config.ssl_ca_path = strdup(optarg);
+        break;
+      case opt_version:
+        printf("version unknown. Could be awesome.\n");
+        break;
+      case opt_help:
+        usage(argv[0]);
+        return 0;
+      default:
+        insist(i == -1, "Flag (--%s%s%s) known, but someone forgot to " \
+               "implement handling of it! This is certainly a bug.",
+               options[i].name,
+               options[i].has_arg ? " " : "",
+               options[i].has_arg ? optarg : "");
+
+        usage(argv[0]);
+        return 1;
+    }
   }

   argc -= optind;
@@ -52,17 +122,16 @@

   /* Start harvesters for each path given */
   for (i = 0; i < argc; i++) {
-    struct harvest_config *config = calloc(1, sizeof(struct harvest_config));
-    config->zmq = zmq;
-    config->zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
-    config->path = argv[i];
-    pthread_create(&harvesters[i], NULL, harvest, config);
+    struct harvest_config *harvester = calloc(1, sizeof(struct harvest_config));
+    harvester->zmq = zmq;
+    harvester->zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
+    harvester->path = argv[i];
+    pthread_create(&harvesters[i], NULL, harvest, harvester);
   }

-  struct emitter_config config;
-  config.zmq = zmq;
-  config.zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
-  emitter(&config);
+  emitter_config.zmq = zmq;
+  emitter_config.zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
+  emitter(&emitter_config);

   /* Wait for the harvesters to die */
   for (i = 0; i < argc; i++) {


git-svn-id: https://www.imagemagick.org/subversion/ImageMagick/trunk@6218 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74

--- MagickCore/composite.c
+++ MagickCore/composite.c
@@ -152,24 +152,24 @@

 /*
    Programmers notes on SVG specification.
-
+
    A Composition is defined by...
      Color Function :  f(Sc,Dc)  where Sc and Dc are the normizalized colors
       Blending areas :  X = 1    for area of overlap   ie: f(Sc,Dc)
                         Y = 1    for source preserved
                         Z = 1    for destination preserved
-
+
    Conversion to transparency (then optimized)
       Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa)
       Da'  = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa)
-
+
    Where...
      Sca = Sc*Sa     normalized Source color divided by Source alpha
      Dca = Dc*Da     normalized Dest color divided by Dest alpha
      Dc' = Dca'/Da'  the desired color value for this channel.
-
+
    Da' (alpha result) is stored as 'gamma' in the functions.
-
+
    The compose functions defined is just simplifications of the above
    formula on a case by case bases.

@@ -179,16 +179,16 @@
    methods should use a 'Over' blending mode for Alpha Channel.
    It however was not applied for composition modes of 'Plus', 'Minus',
    the modulus versions of 'Add' and 'Subtract'.
-
+
    Mathematical operator changes to be applied from IM v6.7...
-
+
     1/ Modulus modes 'Add' and 'Subtract' are obsoleted and renamed
        'ModulusAdd' and 'ModulusSubtract' for clarity.
-
+
     2/ All mathematical compositions work as per the SVG specification
        with regard to blending.  This now includes 'ModulusAdd' and
        'ModulusSubtract'.
-
+
     3/ When the special channel flag 'sync' (syncronize channel updates)
        is turned off (enabled by default) then mathematical compositions are
        only performed on the channels specified, and are applied
@@ -1607,9 +1607,6 @@
   MagickStatusType
     flags;

-  PixelInfo
-    zero;
-
   ssize_t
     y;

@@ -1624,7 +1621,6 @@
   assert(composite_image->signature == MagickSignature);
   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
     return(MagickFalse);
-  GetPixelInfo(image,&zero);
   destination_image=(Image *) NULL;
   amount=0.5;
   destination_dissolve=1.0;
@@ -1636,13 +1632,13 @@
   switch (compose)
   {
     case ClearCompositeOp:
+    case DstAtopCompositeOp:
+    case DstInCompositeOp:
+    case InCompositeOp:
+    case OutCompositeOp:
     case SrcCompositeOp:
-    case InCompositeOp:
     case SrcInCompositeOp:
-    case OutCompositeOp:
     case SrcOutCompositeOp:
-    case DstInCompositeOp:
-    case DstAtopCompositeOp:
     {
       /*
         Modify destination outside the overlaid region.
@@ -1804,7 +1800,6 @@
       /*
         Blur Image by resampling.
       */
-      pixel=zero;
       resample_filter=AcquireResampleFilter(image,exception);
       SetResampleFilter(resample_filter,CubicFilter,2.0);
       destination_view=AcquireCacheView(destination_image);
@@ -1976,7 +1971,7 @@
         Shift the pixel offset point as defined by the provided,
         displacement/distortion map.  -- Like a lens...
       */
-      pixel=zero;
+      GetPixelInfo(image,&pixel);
       image_view=AcquireCacheView(image);
       destination_view=AcquireCacheView(destination_image);
       composite_view=AcquireCacheView(composite_image);
@@ -2150,11 +2145,10 @@
   status=MagickTrue;
   progress=0;
   midpoint=((MagickRealType) QuantumRange+1.0)/2;
-  GetPixelInfo(composite_image,&zero);
   image_view=AcquireCacheView(image);
   composite_view=AcquireCacheView(composite_image);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
+//  #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -2166,11 +2160,6 @@
       hue,
       saturation;

-    PixelInfo
-      composite,
-      destination,
-      source;
-
     register const Quantum
       *restrict p;

@@ -2179,6 +2168,8 @@

     register ssize_t
       x;
+
+MagickBooleanType composite_channels;

     if (status == MagickFalse)
       continue;
@@ -2213,8 +2204,6 @@
         status=MagickFalse;
         continue;
       }
-    source=zero;
-    destination=zero;
     hue=0.0;
     saturation=0.0;
     brightness=0.0;
@@ -2230,494 +2219,792 @@
           if ((x-x_offset) >= (ssize_t) composite_image->columns)
             break;
         }
-      destination.red=(MagickRealType) GetPixelRed(image,q);
-      destination.green=(MagickRealType) GetPixelGreen(image,q);
-      destination.blue=(MagickRealType) GetPixelBlue(image,q);
-      if (image->colorspace == CMYKColorspace)
-        destination.black=(MagickRealType) GetPixelBlack(image,q);
-      if (image->colorspace == CMYKColorspace)
-        {
-          destination.red=(MagickRealType) QuantumRange-destination.red;
-          destination.green=(MagickRealType) QuantumRange-destination.green;
-          destination.blue=(MagickRealType) QuantumRange-destination.blue;
-          destination.black=(MagickRealType) QuantumRange-destination.black;
-        }
-      if (image->matte != MagickFalse)
-        destination.alpha=(MagickRealType) GetPixelAlpha(image,q);
-      /*
-        Handle destination modifications outside overlaid region.
-      */
-      composite=destination;
-      if ((pixels == (Quantum *) NULL) || (x < x_offset) ||
-          ((x-x_offset) >= (ssize_t) composite_image->columns))
-        {
-          switch (compose)
-          {
-            case DissolveCompositeOp:
-            case BlendCompositeOp:
-            {
-              composite.alpha=destination_dissolve*(composite.alpha);
-              break;
-            }
-            case ClearCompositeOp:
-            case SrcCompositeOp:
-            {
-              CompositeClear(&destination,&composite);
-              break;
-            }
-            case InCompositeOp:
-            case SrcInCompositeOp:
-            case OutCompositeOp:
-            case SrcOutCompositeOp:
-            case DstInCompositeOp:
-            case DstAtopCompositeOp:
-            case CopyOpacityCompositeOp:
-            case ChangeMaskCompositeOp:
-            {
-              composite.alpha=(MagickRealType) TransparentAlpha;
-              break;
-            }
-            default:
-            {
-              (void) GetOneVirtualPixelInfo(composite_image,
-                GetPixelCacheVirtualMethod(composite_image),x-x_offset,y-
-                y_offset,&composite,exception);
-              break;
-            }
-          }
-          if (image->colorspace == CMYKColorspace)
-            {
-              composite.red=(MagickRealType) QuantumRange-composite.red;
-              composite.green=(MagickRealType) QuantumRange-composite.green;
-              composite.blue=(MagickRealType) QuantumRange-composite.blue;
-              composite.black=(MagickRealType) QuantumRange-composite.black;
-            }
-          SetPixelRed(image,ClampToQuantum(composite.red),q);
-          SetPixelGreen(image,ClampToQuantum(composite.green),q);
-          SetPixelBlue(image,ClampToQuantum(composite.blue),q);
-          if (image->matte != MagickFalse)
-            SetPixelAlpha(image,ClampToQuantum(composite.alpha),q);
-          if (image->colorspace == CMYKColorspace)
-            SetPixelBlack(image,ClampToQuantum(composite.black),q);
-          q+=GetPixelChannels(image);
-          continue;
-        }
-      /*
-        Handle normal overlay of source onto destination.
-      */
-      source.red=(MagickRealType) GetPixelRed(composite_image,p);
-      source.green=(MagickRealType) GetPixelGreen(composite_image,p);
-      source.blue=(MagickRealType) GetPixelBlue(composite_image,p);
-      if (composite_image->colorspace == CMYKColorspace)
-        source.black=(MagickRealType) GetPixelBlack(composite_image,p);
-      if (composite_image->colorspace == CMYKColorspace)
-        {
-          source.red=(MagickRealType) QuantumRange-source.red;
-          source.green=(MagickRealType) QuantumRange-source.green;
-          source.blue=(MagickRealType) QuantumRange-source.blue;
-          source.black=(MagickRealType) QuantumRange-source.black;
-        }
-      if (composite_image->matte != MagickFalse)
-        source.alpha=(MagickRealType) GetPixelAlpha(composite_image,p);
-      /*
-        Porter-Duff compositions.
-      */
+      composite_channels=MagickFalse;
       switch (compose)
       {
+        case AtopCompositeOp:
         case ClearCompositeOp:
-        {
-          CompositeClear(&destination,&composite);
-          break;
-        }
+        case CopyCompositeOp:
+        case DstAtopCompositeOp:
+        case DstCompositeOp:
+        case DstInCompositeOp:
+        case DstOverCompositeOp:
+        case DstOutCompositeOp:
+        case InCompositeOp:
+        case OutCompositeOp:
+        case OverCompositeOp:
+        case ReplaceCompositeOp:
+        case SrcAtopCompositeOp:
         case SrcCompositeOp:
-        case CopyCompositeOp:
-        case ReplaceCompositeOp:
-        {
-          composite=source;
-          break;
-        }
-        case NoCompositeOp:
-        case DstCompositeOp:
-          break;
-        case OverCompositeOp:
+        case SrcInCompositeOp:
+        case SrcOutCompositeOp:
         case SrcOverCompositeOp:
-        {
-          CompositePixelInfoOver(&source,source.alpha,&destination,
-            destination.alpha,&composite);
-          break;
-        }
-        case DstOverCompositeOp:
-        {
-          CompositePixelInfoOver(&destination,destination.alpha,&source,
-            source.alpha,&composite);
-          break;
-        }
-        case SrcInCompositeOp:
-        case InCompositeOp:
-        {
-          CompositeIn(&source,&destination,&composite);
-          break;
-        }
-        case DstInCompositeOp:
-        {
-          CompositeIn(&destination,&source,&composite);
-          break;
-        }
-        case OutCompositeOp:
-        case SrcOutCompositeOp:
-        {
-          CompositeOut(&source,&destination,&composite);
-          break;
-        }
-        case DstOutCompositeOp:
-        {
-          CompositeOut(&destination,&source,&composite);
-          break;
-        }
-        case AtopCompositeOp:
-        case SrcAtopCompositeOp:
-        {
-          CompositeAtop(&source,&destination,&composite);
-          break;
-        }
-        case DstAtopCompositeOp:
-        {
-          CompositeAtop(&destination,&source,&composite);
-          break;
-        }
         case XorCompositeOp:
         {
-          CompositeXor(&source,&destination,&composite);
-          break;
-        }
-        case PlusCompositeOp:
-        {
-          CompositePlus(image,&source,&destination,&composite);
-          break;
-        }
-        case MinusDstCompositeOp:
-        {
-          CompositeMinus(image,&source,&destination,&composite);
-          break;
-        }
-        case MinusSrcCompositeOp:
-        {
-          CompositeMinus(image,&destination,&source,&composite);
-          break;
-        }
-        case ModulusAddCompositeOp:
-        {
-          CompositeModulusAdd(image,&source,&destination,&composite);
-          break;
-        }
-        case ModulusSubtractCompositeOp:
-        {
-          CompositeModulusSubtract(image,&source,&destination,&composite);
-          break;
-        }
-        case DifferenceCompositeOp:
-        {
-          CompositeDifference(image,&source,&destination,&composite);
-          break;
-        }
-        case ExclusionCompositeOp:
-        {
-          CompositeExclusion(image,&source,&destination,&composite);
-          break;
-        }
-        case MultiplyCompositeOp:
-        {
-          CompositeMultiply(image,&source,&destination,&composite);
-          break;
-        }
-        case ScreenCompositeOp:
-        {
-          CompositeScreen(image,&source,&destination,&composite);
-          break;
-        }
-        case DivideDstCompositeOp:
-        {
-          CompositeDivide(image,&source,&destination,&composite);
-          break;
-        }
-        case DivideSrcCompositeOp:
-        {
-          CompositeDivide(image,&destination,&source,&composite);
-          break;
-        }
-        case DarkenCompositeOp:
-        {
-          CompositeDarken(image,&source,&destination,&composite);
-          break;
-        }
-        case LightenCompositeOp:
-        {
-          CompositeLighten(image,&source,&destination,&composite);
-          break;
-        }
-        case DarkenIntensityCompositeOp:
-        {
-          CompositeDarkenIntensity(image,&source,&destination,&composite);
-          break;
-        }
-        case LightenIntensityCompositeOp:
-        {
-          CompositeLightenIntensity(image,&source,&destination,&composite);
-          break;
-        }
-        case MathematicsCompositeOp:
-        {
-          CompositeMathematics(image,&source,&destination,&geometry_info,
-            &composite);
-          break;
-        }
-        case ColorDodgeCompositeOp:
-        {
-          CompositeColorDodge(&source,&destination,&composite);
-          break;
-        }
-        case ColorBurnCompositeOp:
-        {
-          CompositeColorBurn(&source,&destination,&composite);
-          break;
-        }
-        case LinearDodgeCompositeOp:
-        {
-          CompositeLinearDodge(&source,&destination,&composite);
-          break;
-        }
-        case LinearBurnCompositeOp:
-        {
-          CompositeLinearBurn(&source,&destination,&composite);
-          break;
-        }
-        case HardLightCompositeOp:
-        {
-          CompositeHardLight(&source,&destination,&composite);
-          break;
-        }
-        case OverlayCompositeOp:
-        {
-          CompositeHardLight(&destination,&source,&composite);
-          break;
-        }
-        case SoftLightCompositeOp:
-        {
-          CompositeSoftLight(&source,&destination,&composite);
-          break;
-        }
-        case LinearLightCompositeOp:
-        {
-          CompositeLinearLight(&source,&destination,&composite);
-          break;
-        }
-        case PegtopLightCompositeOp:
-        {
-          CompositePegtopLight(&source,&destination,&composite);
-          break;
-        }
-        case VividLightCompositeOp:
-        {
-          CompositeVividLight(&source,&destination,&composite);
-          break;
-        }
-        case PinLightCompositeOp:
-        {
-          CompositePinLight(&source,&destination,&composite);
-          break;
-        }
-        case ChangeMaskCompositeOp:
-        {
-          if ((composite.alpha > ((MagickRealType) QuantumRange/2.0)) ||
-              (IsFuzzyEquivalencePixelInfo(&source,&destination) != MagickFalse))
-            composite.alpha=(MagickRealType) TransparentAlpha;
-          else
-            composite.alpha=(MagickRealType) OpaqueAlpha;
-          break;
-        }
-        case BumpmapCompositeOp:
-        {
-          if (source.alpha == TransparentAlpha)
-            break;
-          CompositeBumpmap(&source,&destination,&composite);
-          break;
-        }
-        case DissolveCompositeOp:
-        {
-          CompositePixelInfoOver(&source,source_dissolve*source.alpha,
-            &destination,(MagickRealType) (destination_dissolve*
-            destination.alpha),&composite);
-          break;
-        }
-        case BlendCompositeOp:
-        {
-          CompositePixelInfoBlend(&source,source_dissolve,&destination,
-            destination_dissolve,&composite);
-          break;
-        }
-        case ThresholdCompositeOp:
-        {
-          CompositeThreshold(&source,&destination,threshold,amount,&composite);
-          break;
-        }
-        case ModulateCompositeOp:
-        {
-          double
-            blue,
-            green,
-            red;
-
-          ssize_t
-            offset;
-
-          if (source.alpha == TransparentAlpha)
-            break;
-          offset=(ssize_t) (GetPixelInfoIntensity(&source)-midpoint);
-          if (offset == 0)
-            break;
-          CompositeHSB(destination.red,destination.green,destination.blue,&hue,
-            &saturation,&brightness);
-          brightness+=(0.01*percent_brightness*offset)/midpoint;
-          saturation*=0.01*percent_saturation;
-          HSBComposite(hue,saturation,brightness,&red,&green,&blue);
-          composite.red=red;
-          composite.green=green;
-          composite.blue=blue;
-          break;
-        }
-        case HueCompositeOp:
-        {
-          if (source.alpha == TransparentAlpha)
-            break;
-          if (destination.alpha == TransparentAlpha)
-            {
-              composite=source;
-              break;
-            }
-          CompositeHSB(destination.red,destination.green,destination.blue,&hue,
-            &saturation,&brightness);
-          CompositeHSB(source.red,source.green,source.blue,&hue,&sans,&sans);
-          HSBComposite(hue,saturation,brightness,&composite.red,
-            &composite.green,&composite.blue);
-          if (source.alpha < destination.alpha)
-            composite.alpha=source.alpha;
-          break;
-        }
-        case SaturateCompositeOp:
-        {
-          if (source.alpha == TransparentAlpha)
-            break;
-          if (destination.alpha == TransparentAlpha)
-            {
-              composite=source;
-              break;
-            }
-          CompositeHSB(destination.red,destination.green,destination.blue,&hue,
-            &saturation,&brightness);
-          CompositeHSB(source.red,source.green,source.blue,&sans,&saturation,
-            &sans);
-          HSBComposite(hue,saturation,brightness,&composite.red,
-            &composite.green,&composite.blue);
-          if (source.alpha < destination.alpha)
-            composite.alpha=source.alpha;
-          break;
-        }
-        case LuminizeCompositeOp:
-        {
-          if (source.alpha == TransparentAlpha)
-            break;
-          if (destination.alpha == TransparentAlpha)
-            {
-              composite=source;
-              break;
-            }
-          CompositeHSB(destination.red,destination.green,destination.blue,&hue,
-            &saturation,&brightness);
-          CompositeHSB(source.red,source.green,source.blue,&sans,&sans,
-            &brightness);
-          HSBComposite(hue,saturation,brightness,&composite.red,
-            &composite.green,&composite.blue);
-          if (source.alpha < destination.alpha)
-            composite.alpha=source.alpha;
-          break;
-        }
-        case ColorizeCompositeOp:
-        {
-          if (source.alpha == TransparentAlpha)
-            break;
-          if (destination.alpha == TransparentAlpha)
-            {
-              composite=source;
-              break;
-            }
-          CompositeHSB(destination.red,destination.green,destination.blue,&sans,
-            &sans,&brightness);
-          CompositeHSB(source.red,source.green,source.blue,&hue,&saturation,
-            &sans);
-          HSBComposite(hue,saturation,brightness,&composite.red,
-            &composite.green,&composite.blue);
-          if (source.alpha < destination.alpha)
-            composite.alpha=source.alpha;
-          break;
-        }
-        case CopyRedCompositeOp:
-        case CopyCyanCompositeOp:
-        {
-          composite.red=source.red;
-          break;
-        }
-        case CopyGreenCompositeOp:
-        case CopyMagentaCompositeOp:
-        {
-          composite.green=source.green;
-          break;
-        }
-        case CopyBlueCompositeOp:
-        case CopyYellowCompositeOp:
-        {
-          composite.blue=source.blue;
-          break;
-        }
-        case CopyOpacityCompositeOp:
-        {
-          if (source.matte == MagickFalse)
-            {
-              composite.alpha=(MagickRealType) GetPixelInfoIntensity(&source);
-              break;
-            }
-          composite.alpha=source.alpha;
-          break;
-        }
-        case CopyBlackCompositeOp:
-        {
-          if (source.colorspace != CMYKColorspace)
-            ConvertRGBToCMYK(&source);
-          composite.black=source.black;
-          break;
-        }
-        case BlurCompositeOp:
-        case DisplaceCompositeOp:
-        case DistortCompositeOp:
-        {
-          composite=source;
+          composite_channels=MagickTrue;
           break;
         }
         default:
           break;
       }
-      if (image->colorspace == CMYKColorspace)
+      if (composite_channels != MagickFalse) {
+        MagickRealType
+          Da,
+          Dc,
+          gamma,
+          Sa,
+          Sc;
+
+        register ssize_t
+          i;
+
+        if ((pixels == (Quantum *) NULL) || (x < x_offset) ||
+            ((x-x_offset) >= (ssize_t) composite_image->columns))
+          {
+            Quantum
+              source[MaxPixelChannels];
+
+            /*
+              Virtual composite:
+                Sc: source color.
+                Dc: destination color.
+            */
+            (void) GetOneVirtualPixel(composite_image,x-x_offset,y-y_offset,
+              source,exception);
+            for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+            {
+              MagickRealType
+                pixel;
+
+              PixelChannel
+                channel;
+
+              PixelTrait
+                traits;
+
+              channel=GetPixelChannelMapChannel(image,i);
+              traits=GetPixelChannelMapTraits(image,channel);
+              if (traits == UndefinedPixelTrait)
+                continue;
+              switch (compose)
+              {
+                case ClearCompositeOp:
+                case CopyCompositeOp:
+                case ReplaceCompositeOp:
+                case SrcCompositeOp:
+                {
+                  pixel=0.0;
+                  if (channel == AlphaPixelChannel)
+                    pixel=(MagickRealType) TransparentAlpha;
+                  break;
+                }
+                case DstAtopCompositeOp:
+                case InCompositeOp:
+                case OutCompositeOp:
+                case SrcInCompositeOp:
+                case SrcOutCompositeOp:
+                {
+                  pixel=(MagickRealType) q[i];
+                  if (channel == AlphaPixelChannel)
+                    pixel=(MagickRealType) TransparentAlpha;
+                  break;
+                }
+                default:
+                {
+                  pixel=source[channel];
+                  break;
+                }
+              }
+              q[i]=ClampToQuantum(pixel);
+            }
+            q+=GetPixelChannels(image);
+            continue;
+          }
+        /*
+          Authentic composite:
+            Sa: source normalized alpha.
+            Da: destination normalized alpha.
+        */
+        Sa=QuantumScale*GetPixelAlpha(composite_image,p);
+        Da=QuantumScale*GetPixelAlpha(image,q);
+        switch (compose)
         {
-          composite.red=(MagickRealType) QuantumRange-composite.red;
-          composite.green=(MagickRealType) QuantumRange-composite.green;
-          composite.blue=(MagickRealType) QuantumRange-composite.blue;
-          composite.black=(MagickRealType) QuantumRange-composite.black;
+          case DstOverCompositeOp:
+          {
+            gamma=Da*(-Sa)+Da+Sa;
+            break;
+          }
+          case DstAtopCompositeOp:
+          case DstInCompositeOp:
+          case InCompositeOp:
+          case SrcInCompositeOp:
+          {
+            gamma=Sa*Da;
+            break;
+          }
+          case DstOutCompositeOp:
+          {
+            gamma=Da*(1.0-Sa);
+            break;
+          }
+          case OutCompositeOp:
+          case SrcOutCompositeOp:
+          {
+            gamma=Sa*(1.0-Da);
+            break;
+          }
+          case OverCompositeOp:
+          case SrcOverCompositeOp:
+          {
+            gamma=Sa*(-Da)+Sa+Da;
+            break;
+          }
+          case XorCompositeOp:
+          {
+            gamma=Sa+Da-2.0*Sa*Da;
+            break;
+          }
+          default:
+          {
+            gamma=1.0;
+            break;
+          }
         }
-      SetPixelRed(image,ClampToQuantum(composite.red),q);
-      SetPixelGreen(image,ClampToQuantum(composite.green),q);
-      SetPixelBlue(image,ClampToQuantum(composite.blue),q);
-      if (image->colorspace == CMYKColorspace)
-        SetPixelBlack(image,ClampToQuantum(composite.black),q);
-      SetPixelAlpha(image,ClampToQuantum(composite.alpha),q);
+        for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+        {
+          MagickRealType
+            pixel;
+
+          PixelChannel
+            channel;
+
+          PixelTrait
+            composite_traits,
+            traits;
+
+          channel=GetPixelChannelMapChannel(image,i);
+          traits=GetPixelChannelMapTraits(image,channel);
+          composite_traits=GetPixelChannelMapTraits(composite_image,channel);
+          if ((traits == UndefinedPixelTrait) ||
+              (composite_traits == UndefinedPixelTrait))
+            continue;
+          /*
+            Sc: source color.
+            Dc: destination color.
+          */
+          Sc=(MagickRealType) GetPixelChannel(composite_image,channel,p);
+          Dc=(MagickRealType) q[i];
+          if ((traits & CopyPixelTrait) != 0)
+            {
+              if (channel != AlphaPixelChannel)
+                {
+                  /*
+                    Copy channel.
+                  */
+                  q[i]=Sc;
+                  continue;
+                }
+              /*
+                Set alpha channel.
+              */
+              pixel=0.0;
+              switch (compose)
+              {
+                case CopyCompositeOp:
+                case DstAtopCompositeOp:
+                case ReplaceCompositeOp:
+                case SrcCompositeOp:
+                {
+                  pixel=QuantumRange*Sa;
+                  break;
+                }
+                case AtopCompositeOp:
+                case SrcAtopCompositeOp:
+                case DstCompositeOp:
+                {
+                  pixel=QuantumRange*Da;
+                  break;
+                }
+                default:
+                {
+                  pixel=QuantumRange*gamma;
+                  break;
+                }
+              }
+              q[i]=ClampToQuantum(pixel);
+              continue;
+            }
+          /*
+            Porter-Duff compositions.
+          */
+          pixel=0.0;
+          switch (compose)
+          {
+            case AtopCompositeOp:
+            case SrcAtopCompositeOp:
+            {
+              pixel=Sc*Sa+Dc*(1.0-Sa);
+              break;
+            }
+            case CopyCompositeOp:
+            case ReplaceCompositeOp:
+            case SrcCompositeOp:
+            {
+              pixel=Sc;
+              break;
+            }
+            case DstAtopCompositeOp:
+            {
+              pixel=Dc*Da+Sc*(1.0-Da);
+              break;
+            }
+            case DstCompositeOp:
+            {
+              pixel=Dc;
+              break;
+            }
+            case DstInCompositeOp:
+            {
+              pixel=gamma*(Sa*Dc*Sa);
+              break;
+            }
+            case DstOutCompositeOp:
+            {
+              pixel=gamma*(Da*Dc*(1.0-Sa));
+              break;
+            }
+            case DstOverCompositeOp:
+            {
+              pixel=gamma*(Da*Dc-Da*Sa*Sc+Sa*Sc);
+              break;
+            }
+            case InCompositeOp:
+            case SrcInCompositeOp:
+            {
+              pixel=gamma*(Da*Sc*Da);
+              break;
+            }
+            case OutCompositeOp:
+            case SrcOutCompositeOp:
+            {
+              pixel=gamma*(Sa*Sc*(1.0-Da));
+              break;
+            }
+            case OverCompositeOp:
+            case SrcOverCompositeOp:
+            {
+              pixel=gamma*(Sa*Sc-Sa*Da*Dc+Da*Dc);
+              break;
+            }
+            case XorCompositeOp:
+            {
+              pixel=gamma*(Sc*Sa*(1.0-Da)+Dc*Da*(1.0-Sa));
+              break;
+            }
+            default:
+              break;
+          }
+          q[i]=ClampToQuantum(pixel);
+        }
+      } else {
+        PixelInfo
+          composite,
+          destination,
+          source,
+          zero;
+
+        GetPixelInfo(image,&zero);
+        source=zero;
+        destination=zero;
+        destination.red=(MagickRealType) GetPixelRed(image,q);
+        destination.green=(MagickRealType) GetPixelGreen(image,q);
+        destination.blue=(MagickRealType) GetPixelBlue(image,q);
+        if (image->colorspace == CMYKColorspace)
+          destination.black=(MagickRealType) GetPixelBlack(image,q);
+        if (image->colorspace == CMYKColorspace)
+          {
+            destination.red=(MagickRealType) QuantumRange-destination.red;
+            destination.green=(MagickRealType) QuantumRange-destination.green;
+            destination.blue=(MagickRealType) QuantumRange-destination.blue;
+            destination.black=(MagickRealType) QuantumRange-destination.black;
+          }
+        if (image->matte != MagickFalse)
+          destination.alpha=(MagickRealType) GetPixelAlpha(image,q);
+        /*
+          Handle destination modifications outside overlaid region.
+        */
+        composite=destination;
+        if ((pixels == (Quantum *) NULL) || (x < x_offset) ||
+            ((x-x_offset) >= (ssize_t) composite_image->columns))
+          {
+            switch (compose)
+            {
+              case DissolveCompositeOp:
+              case BlendCompositeOp:
+              {
+                composite.alpha=destination_dissolve*(composite.alpha);
+                break;
+              }
+              case ClearCompositeOp:
+              case SrcCompositeOp:
+              {
+                CompositeClear(&destination,&composite);
+                break;
+              }
+              case InCompositeOp:
+              case SrcInCompositeOp:
+              case OutCompositeOp:
+              case SrcOutCompositeOp:
+              case DstInCompositeOp:
+              case DstAtopCompositeOp:
+              case CopyOpacityCompositeOp:
+              case ChangeMaskCompositeOp:
+              {
+                composite.alpha=(MagickRealType) TransparentAlpha;
+                break;
+              }
+              default:
+              {
+                (void) GetOneVirtualPixelInfo(composite_image,
+                  GetPixelCacheVirtualMethod(composite_image),x-x_offset,y-
+                  y_offset,&composite,exception);
+                break;
+              }
+            }
+            if (image->colorspace == CMYKColorspace)
+              {
+                composite.red=(MagickRealType) QuantumRange-composite.red;
+                composite.green=(MagickRealType) QuantumRange-composite.green;
+                composite.blue=(MagickRealType) QuantumRange-composite.blue;
+                composite.black=(MagickRealType) QuantumRange-composite.black;
+              }
+            SetPixelRed(image,ClampToQuantum(composite.red),q);
+            SetPixelGreen(image,ClampToQuantum(composite.green),q);
+            SetPixelBlue(image,ClampToQuantum(composite.blue),q);
+            if (image->matte != MagickFalse)
+              SetPixelAlpha(image,ClampToQuantum(composite.alpha),q);
+            if (image->colorspace == CMYKColorspace)
+              SetPixelBlack(image,ClampToQuantum(composite.black),q);
+            q+=GetPixelChannels(image);
+            continue;
+          }
+        /*
+          Handle normal overlay of source onto destination.
+        */
+        source.red=(MagickRealType) GetPixelRed(composite_image,p);
+        source.green=(MagickRealType) GetPixelGreen(composite_image,p);
+        source.blue=(MagickRealType) GetPixelBlue(composite_image,p);
+        if (composite_image->colorspace == CMYKColorspace)
+          source.black=(MagickRealType) GetPixelBlack(composite_image,p);
+        if (composite_image->colorspace == CMYKColorspace)
+          {
+            source.red=(MagickRealType) QuantumRange-source.red;
+            source.green=(MagickRealType) QuantumRange-source.green;
+            source.blue=(MagickRealType) QuantumRange-source.blue;
+            source.black=(MagickRealType) QuantumRange-source.black;
+          }
+        if (composite_image->matte != MagickFalse)
+          source.alpha=(MagickRealType) GetPixelAlpha(composite_image,p);
+        /*
+          Porter-Duff compositions.
+        */
+        switch (compose)
+        {
+          case ClearCompositeOp:
+          {
+            CompositeClear(&destination,&composite);
+            break;
+          }
+          case SrcCompositeOp:
+          case CopyCompositeOp:
+          case ReplaceCompositeOp:
+          {
+            composite=source;
+            break;
+          }
+          case NoCompositeOp:
+          case DstCompositeOp:
+            break;
+          case OverCompositeOp:
+          case SrcOverCompositeOp:
+          {
+            CompositePixelInfoOver(&source,source.alpha,&destination,
+              destination.alpha,&composite);
+            break;
+          }
+          case DstOverCompositeOp:
+          {
+            CompositePixelInfoOver(&destination,destination.alpha,&source,
+              source.alpha,&composite);
+            break;
+          }
+          case SrcInCompositeOp:
+          case InCompositeOp:
+          {
+            CompositeIn(&source,&destination,&composite);
+            break;
+          }
+          case DstInCompositeOp:
+          {
+            CompositeIn(&destination,&source,&composite);
+            break;
+          }
+          case OutCompositeOp:
+          case SrcOutCompositeOp:
+          {
+            CompositeOut(&source,&destination,&composite);
+            break;
+          }
+          case DstOutCompositeOp:
+          {
+            CompositeOut(&destination,&source,&composite);
+            break;
+          }
+          case AtopCompositeOp:
+          case SrcAtopCompositeOp:
+          {
+            CompositeAtop(&source,&destination,&composite);
+            break;
+          }
+          case DstAtopCompositeOp:
+          {
+            CompositeAtop(&destination,&source,&composite);
+            break;
+          }
+          case XorCompositeOp:
+          {
+            CompositeXor(&source,&destination,&composite);
+            break;
+          }
+          case PlusCompositeOp:
+          {
+            CompositePlus(image,&source,&destination,&composite);
+            break;
+          }
+          case MinusDstCompositeOp:
+          {
+            CompositeMinus(image,&source,&destination,&composite);
+            break;
+          }
+          case MinusSrcCompositeOp:
+          {
+            CompositeMinus(image,&destination,&source,&composite);
+            break;
+          }
+          case ModulusAddCompositeOp:
+          {
+            CompositeModulusAdd(image,&source,&destination,&composite);
+            break;
+          }
+          case ModulusSubtractCompositeOp:
+          {
+            CompositeModulusSubtract(image,&source,&destination,&composite);
+            break;
+          }
+          case DifferenceCompositeOp:
+          {
+            CompositeDifference(image,&source,&destination,&composite);
+            break;
+          }
+          case ExclusionCompositeOp:
+          {
+            CompositeExclusion(image,&source,&destination,&composite);
+            break;
+          }
+          case MultiplyCompositeOp:
+          {
+            CompositeMultiply(image,&source,&destination,&composite);
+            break;
+          }
+          case ScreenCompositeOp:
+          {
+            CompositeScreen(image,&source,&destination,&composite);
+            break;
+          }
+          case DivideDstCompositeOp:
+          {
+            CompositeDivide(image,&source,&destination,&composite);
+            break;
+          }
+          case DivideSrcCompositeOp:
+          {
+            CompositeDivide(image,&destination,&source,&composite);
+            break;
+          }
+          case DarkenCompositeOp:
+          {
+            CompositeDarken(image,&source,&destination,&composite);
+            break;
+          }
+          case LightenCompositeOp:
+          {
+            CompositeLighten(image,&source,&destination,&composite);
+            break;
+          }
+          case DarkenIntensityCompositeOp:
+          {
+            CompositeDarkenIntensity(image,&source,&destination,&composite);
+            break;
+          }
+          case LightenIntensityCompositeOp:
+          {
+            CompositeLightenIntensity(image,&source,&destination,&composite);
+            break;
+          }
+          case MathematicsCompositeOp:
+          {
+            CompositeMathematics(image,&source,&destination,&geometry_info,
+              &composite);
+            break;
+          }
+          case ColorDodgeCompositeOp:
+          {
+            CompositeColorDodge(&source,&destination,&composite);
+            break;
+          }
+          case ColorBurnCompositeOp:
+          {
+            CompositeColorBurn(&source,&destination,&composite);
+            break;
+          }
+          case LinearDodgeCompositeOp:
+          {
+            CompositeLinearDodge(&source,&destination,&composite);
+            break;
+          }
+          case LinearBurnCompositeOp:
+          {
+            CompositeLinearBurn(&source,&destination,&composite);
+            break;
+          }
+          case HardLightCompositeOp:
+          {
+            CompositeHardLight(&source,&destination,&composite);
+            break;
+          }
+          case OverlayCompositeOp:
+          {
+            CompositeHardLight(&destination,&source,&composite);
+            break;
+          }
+          case SoftLightCompositeOp:
+          {
+            CompositeSoftLight(&source,&destination,&composite);
+            break;
+          }
+          case LinearLightCompositeOp:
+          {
+            CompositeLinearLight(&source,&destination,&composite);
+            break;
+          }
+          case PegtopLightCompositeOp:
+          {
+            CompositePegtopLight(&source,&destination,&composite);
+            break;
+          }
+          case VividLightCompositeOp:
+          {
+            CompositeVividLight(&source,&destination,&composite);
+            break;
+          }
+          case PinLightCompositeOp:
+          {
+            CompositePinLight(&source,&destination,&composite);
+            break;
+          }
+          case ChangeMaskCompositeOp:
+          {
+            if ((composite.alpha > ((MagickRealType) QuantumRange/2.0)) ||
+                (IsFuzzyEquivalencePixelInfo(&source,&destination) != MagickFalse))
+              composite.alpha=(MagickRealType) TransparentAlpha;
+            else
+              composite.alpha=(MagickRealType) OpaqueAlpha;
+            break;
+          }
+          case BumpmapCompositeOp:
+          {
+            if (source.alpha == TransparentAlpha)
+              break;
+            CompositeBumpmap(&source,&destination,&composite);
+            break;
+          }
+          case DissolveCompositeOp:
+          {
+            CompositePixelInfoOver(&source,source_dissolve*source.alpha,
+              &destination,(MagickRealType) (destination_dissolve*
+              destination.alpha),&composite);
+            break;
+          }
+          case BlendCompositeOp:
+          {
+            CompositePixelInfoBlend(&source,source_dissolve,&destination,
+              destination_dissolve,&composite);
+            break;
+          }
+          case ThresholdCompositeOp:
+          {
+            CompositeThreshold(&source,&destination,threshold,amount,&composite);
+            break;
+          }
+          case ModulateCompositeOp:
+          {
+            double
+              blue,
+              green,
+              red;
+
+            ssize_t
+              offset;
+
+            if (source.alpha == TransparentAlpha)
+              break;
+            offset=(ssize_t) (GetPixelInfoIntensity(&source)-midpoint);
+            if (offset == 0)
+              break;
+            CompositeHSB(destination.red,destination.green,destination.blue,&hue,
+              &saturation,&brightness);
+            brightness+=(0.01*percent_brightness*offset)/midpoint;
+            saturation*=0.01*percent_saturation;
+            HSBComposite(hue,saturation,brightness,&red,&green,&blue);
+            composite.red=red;
+            composite.green=green;
+            composite.blue=blue;
+            break;
+          }
+          case HueCompositeOp:
+          {
+            if (source.alpha == TransparentAlpha)
+              break;
+            if (destination.alpha == TransparentAlpha)
+              {
+                composite=source;
+                break;
+              }
+            CompositeHSB(destination.red,destination.green,destination.blue,&hue,
+              &saturation,&brightness);
+            CompositeHSB(source.red,source.green,source.blue,&hue,&sans,&sans);
+            HSBComposite(hue,saturation,brightness,&composite.red,
+              &composite.green,&composite.blue);
+            if (source.alpha < destination.alpha)
+              composite.alpha=source.alpha;
+            break;
+          }
+          case SaturateCompositeOp:
+          {
+            if (source.alpha == TransparentAlpha)
+              break;
+            if (destination.alpha == TransparentAlpha)
+              {
+                composite=source;
+                break;
+              }
+            CompositeHSB(destination.red,destination.green,destination.blue,&hue,
+              &saturation,&brightness);
+            CompositeHSB(source.red,source.green,source.blue,&sans,&saturation,
+              &sans);
+            HSBComposite(hue,saturation,brightness,&composite.red,
+              &composite.green,&composite.blue);
+            if (source.alpha < destination.alpha)
+              composite.alpha=source.alpha;
+            break;
+          }
+          case LuminizeCompositeOp:
+          {
+            if (source.alpha == TransparentAlpha)
+              break;
+            if (destination.alpha == TransparentAlpha)
+              {
+                composite=source;
+                break;
+              }
+            CompositeHSB(destination.red,destination.green,destination.blue,&hue,
+              &saturation,&brightness);
+            CompositeHSB(source.red,source.green,source.blue,&sans,&sans,
+              &brightness);
+            HSBComposite(hue,saturation,brightness,&composite.red,
+              &composite.green,&composite.blue);
+            if (source.alpha < destination.alpha)
+              composite.alpha=source.alpha;
+            break;
+          }
+          case ColorizeCompositeOp:
+          {
+            if (source.alpha == TransparentAlpha)
+              break;
+            if (destination.alpha == TransparentAlpha)
+              {
+                composite=source;
+                break;
+              }
+            CompositeHSB(destination.red,destination.green,destination.blue,&sans,
+              &sans,&brightness);
+            CompositeHSB(source.red,source.green,source.blue,&hue,&saturation,
+              &sans);
+            HSBComposite(hue,saturation,brightness,&composite.red,
+              &composite.green,&composite.blue);
+            if (source.alpha < destination.alpha)
+              composite.alpha=source.alpha;
+            break;
+          }
+          case CopyRedCompositeOp:
+          case CopyCyanCompositeOp:
+          {
+            composite.red=source.red;
+            break;
+          }
+          case CopyGreenCompositeOp:
+          case CopyMagentaCompositeOp:
+          {
+            composite.green=source.green;
+            break;
+          }
+          case CopyBlueCompositeOp:
+          case CopyYellowCompositeOp:
+          {
+            composite.blue=source.blue;
+            break;
+          }
+          case CopyOpacityCompositeOp:
+          {
+            if (source.matte == MagickFalse)
+              {
+                composite.alpha=(MagickRealType) GetPixelInfoIntensity(&source);
+                break;
+              }
+            composite.alpha=source.alpha;
+            break;
+          }
+          case CopyBlackCompositeOp:
+          {
+            if (source.colorspace != CMYKColorspace)
+              ConvertRGBToCMYK(&source);
+            composite.black=source.black;
+            break;
+          }
+          case BlurCompositeOp:
+          case DisplaceCompositeOp:
+          case DistortCompositeOp:
+          {
+            composite=source;
+            break;
+          }
+          default:
+            break;
+        }
+        if (image->colorspace == CMYKColorspace)
+          {
+            composite.red=(MagickRealType) QuantumRange-composite.red;
+            composite.green=(MagickRealType) QuantumRange-composite.green;
+            composite.blue=(MagickRealType) QuantumRange-composite.blue;
+            composite.black=(MagickRealType) QuantumRange-composite.black;
+          }
+        SetPixelRed(image,ClampToQuantum(composite.red),q);
+        SetPixelGreen(image,ClampToQuantum(composite.green),q);
+        SetPixelBlue(image,ClampToQuantum(composite.blue),q);
+        if (image->colorspace == CMYKColorspace)
+          SetPixelBlack(image,ClampToQuantum(composite.black),q);
+        SetPixelAlpha(image,ClampToQuantum(composite.alpha),q);
+      }
       p+=GetPixelChannels(composite_image);
       if (p >= (pixels+composite_image->columns*GetPixelChannels(composite_image)))
         p=pixels;


git-svn-id: https://www.imagemagick.org/subversion/ImageMagick/trunk@14079 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74

--- MagickCore/threshold.c
+++ MagickCore/threshold.c
@@ -977,7 +977,10 @@
       break;
   }
   if (threshold == (XMLTreeInfo *) NULL)
-    return(map);
+    {
+      thresholds=DestroyXMLTree(thresholds);
+      return(map);
+    }
   description=GetXMLTreeChild(threshold,"description");
   if (description == (XMLTreeInfo *) NULL)
     {


git-svn-id: https://www.imagemagick.org/subversion/ImageMagick/trunk@8664 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74

--- MagickCore/threshold.c
+++ MagickCore/threshold.c
@@ -591,6 +591,9 @@
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
+      double
+        pixel;
+
       register ssize_t
         i;

@@ -599,6 +602,7 @@
           q+=GetPixelChannels(image);
           continue;
         }
+      pixel=(double) GetPixelIntensity(image,q);
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
         PixelChannel
@@ -611,7 +615,9 @@
         traits=GetPixelChannelMapTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if ((double) q[i] <= GetPixelInfoChannel(&threshold,channel))
+        if (image->channel_mask != DefaultChannels)
+          pixel=q[i];
+        if (pixel <= GetPixelInfoChannel(&threshold,channel))
           q[i]=0;
       }
       q+=GetPixelChannels(image);
@@ -1733,6 +1739,9 @@
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
+      double
+        pixel;
+
       register ssize_t
         i;

@@ -1741,6 +1750,7 @@
           q+=GetPixelChannels(image);
           continue;
         }
+      pixel=(double) GetPixelIntensity(image,q);
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
         PixelChannel
@@ -1753,7 +1763,9 @@
         traits=GetPixelChannelMapTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if ((double) q[i] > GetPixelInfoChannel(&threshold,channel))
+        if (image->channel_mask != DefaultChannels)
+          pixel=q[i];
+        if (pixel > GetPixelInfoChannel(&threshold,channel))
           q[i]=QuantumRange;
       }
       q+=GetPixelChannels(image);


git-svn-id: https://www.imagemagick.org/subversion/ImageMagick/trunk@17755 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74

--- MagickWand/operation.c
+++ MagickWand/operation.c
@@ -4209,9 +4209,9 @@
             count;

           /* convert argument string into an array of doubles */
-          args = StringToArrayOfDoubles(arg2,&count,_exception);
+          args = StringToArrayOfDoubles(arg1,&count,_exception);
           if (args == (double *) NULL )
-            CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg2);
+            CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg1);
           new_images=PolynomialImage(_images,(size_t) (count >> 1),args,_exception);
           args=(double *) RelinquishMagickMemory(args);
           break;


Added bt_piece_db_add_pieces test case

Added bt_piece_db_add_pieces test case

--- tests/test_piece_db.c
+++ tests/test_piece_db.c
@@ -83,6 +83,21 @@
     CuAssertTrue(tc, 4 == bt_piecedb_get_length(db));
 }

+void TestBTPieceDB_add_pieces(CuTest * tc)
+{
+    void *db;
+
+    db = bt_piecedb_new();
+    //bt_piecedb_set_piece_length(db, 40);
+    /* need to add a file so that we have a filespace to hold the added piece */
+    bt_piecedb_increase_piece_space(db,40);
+    //bt_piecedb_add(db, "00000000000000000000", 40);
+    bt_piecedb_add(db, 2);// "00000000000000000000", 40);
+    CuAssertTrue(tc, 2 == bt_piecedb_count(db));
+    CuAssertTrue(tc, NULL != bt_piecedb_get(db, 0));
+    CuAssertTrue(tc, NULL != bt_piecedb_get(db, 1));
+}
+
 #if 0
 void T_estBTPieceDB_AddingPiece_LastPieceFitsTotalSize(
     CuTest * tc


Add isNegative to RationalNumberType

Add isNegative to RationalNumberType

--- libsolidity/ast/Types.h
+++ libsolidity/ast/Types.h
@@ -411,6 +411,9 @@
 	/// @returns true if the value is not an integer.
 	bool isFractional() const { return m_value.denominator() != 1; }

+	/// @returns true if the value is negative.
+	bool isNegative() const { return m_value < 0; }
+
 private:
 	rational m_value;
 };


testicontheme: Add some tests for scales

--- tests/testicontheme.c
+++ tests/testicontheme.c
@@ -24,11 +24,11 @@
 static void
 usage (void)
 {
-  g_print ("usage: test-icon-theme lookup <theme name> <icon name> [size]]\n"
+  g_print ("usage: test-icon-theme lookup <theme name> <icon name> [size] [scale]\n"
 	   " or\n"
 	   "usage: test-icon-theme list <theme name> [context]\n"
 	   " or\n"
-	   "usage: test-icon-theme display <theme name> <icon name> [size]\n"
+	   "usage: test-icon-theme display <theme name> <icon name> [size] [scale]\n"
 	   " or\n"
 	   "usage: test-icon-theme contexts <theme name>\n"
 	   );
@@ -70,6 +70,7 @@
   char *themename;
   GList *list;
   int size = 48;
+  int scale = 1;
   int i;

   gtk_init (&argc, &argv);
@@ -91,7 +92,6 @@
       GError *error;
       GdkPixbuf *pixbuf;
       GtkWidget *window, *image;
-      GtkIconSize size;

       if (argc < 4)
 	{
@@ -102,12 +102,13 @@

       if (argc >= 5)
 	size = atoi (argv[4]);
-      else
-	size = GTK_ICON_SIZE_BUTTON;
+
+      if (argc >= 6)
+	scale = atoi (argv[5]);

       error = NULL;
-      pixbuf = gtk_icon_theme_load_icon (icon_theme, argv[3], size,
-                                         GTK_ICON_LOOKUP_USE_BUILTIN, &error);
+      pixbuf = gtk_icon_theme_load_icon_for_scale (icon_theme, argv[3], size, scale,
+                                                   GTK_ICON_LOOKUP_USE_BUILTIN, &error);
       if (!pixbuf)
         {
           g_print ("%s\n", error->message);
@@ -128,7 +129,6 @@
   else if (strcmp (argv[1], "display-async") == 0)
     {
       GtkWidget *window, *image;
-      GtkIconSize size;
       GtkIconInfo *info;

       if (argc < 4)
@@ -140,8 +140,9 @@

       if (argc >= 5)
 	size = atoi (argv[4]);
-      else
-	size = GTK_ICON_SIZE_BUTTON;
+
+      if (argc >= 6)
+	scale = atoi (argv[5]);

       window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
       image = gtk_image_new ();
@@ -150,8 +151,8 @@
                         G_CALLBACK (gtk_main_quit), window);
       gtk_widget_show_all (window);

-      info = gtk_icon_theme_lookup_icon (icon_theme, argv[3], size,
-                                         GTK_ICON_LOOKUP_USE_BUILTIN);
+      info = gtk_icon_theme_lookup_icon_for_scale (icon_theme, argv[3], size, scale,
+                                                   GTK_ICON_LOOKUP_USE_BUILTIN);

       if (info == NULL)
 	{
@@ -198,16 +199,30 @@
 	  usage ();
 	  return 1;
 	}
-
+
       if (argc >= 5)
 	size = atoi (argv[4]);
-
-      icon_info = gtk_icon_theme_lookup_icon (icon_theme, argv[3], size, GTK_ICON_LOOKUP_USE_BUILTIN);
-      g_print ("icon for %s at %dx%d is %s\n", argv[3], size, size,
+
+      if (argc >= 6)
+	scale = atoi (argv[5]);
+
+      icon_info = gtk_icon_theme_lookup_icon_for_scale (icon_theme, argv[3], size, scale, GTK_ICON_LOOKUP_USE_BUILTIN);
+      g_print ("icon for %s at %dx%d@%dx is %s\n", argv[3], size, size, scale,
 	       icon_info ? (gtk_icon_info_get_builtin_pixbuf (icon_info) ? "<builtin>" : gtk_icon_info_get_filename (icon_info)) : "<none>");

-      if (icon_info)
-	{
+      if (icon_info)
+	{
+          GdkPixbuf *pixbuf;
+
+          g_print ("Base size: %d, Scale: %d\n", gtk_icon_info_get_base_size (icon_info), gtk_icon_info_get_base_scale (icon_info));
+
+          pixbuf = gtk_icon_info_load_icon (icon_info, NULL);
+          if (pixbuf != NULL)
+            {
+              g_print ("Pixbuf size: %dx%d\n", gdk_pixbuf_get_width (pixbuf), gdk_pixbuf_get_height (pixbuf));
+              g_object_unref (pixbuf);
+            }
+
 	  if (gtk_icon_info_get_embedded_rect (icon_info, &embedded_rect))
 	    {
 	      g_print ("Embedded rect: %d,%d %dx%d\n",


tests: gpiomon: new test case for watching multiple lines

Make sure gpiomon behaves correctly when the requested line offsets
are not in order.

Signed-off-by: Bartosz Golaszewski <108de5fbc428215dc26df4468b48691526611148@gmail.com>

--- tests/tests-gpiomon.c
+++ tests/tests-gpiomon.c
@@ -175,6 +175,30 @@
 	    "tools: gpiomon - watch multiple lines",
 	    0, { 8, 8 });

+static void gpiomon_watch_multiple_lines_not_in_order(void)
+{
+	test_tool_run("gpiomon", "--format=%o", test_chip_name(0),
+		      "5", "2", "7", "1", "6", (char *)NULL);
+	test_set_event(0, 2, TEST_EVENT_ALTERNATING, 100);
+	usleep(150000);
+	test_set_event(0, 1, TEST_EVENT_ALTERNATING, 100);
+	usleep(150000);
+	test_set_event(0, 6, TEST_EVENT_ALTERNATING, 100);
+	usleep(150000);
+	test_tool_signal(SIGTERM);
+	test_tool_wait();
+
+	TEST_ASSERT(test_tool_exited());
+	TEST_ASSERT_RET_OK(test_tool_exit_status());
+	TEST_ASSERT_NULL(test_tool_stderr());
+	TEST_ASSERT_NOT_NULL(test_tool_stdout());
+	TEST_ASSERT_STR_EQ(test_tool_stdout(), "2\n1\n6\n");
+
+}
+TEST_DEFINE(gpiomon_watch_multiple_lines_not_in_order,
+	    "tools: gpiomon - watch multiple lines (offsets not in order)",
+	    0, { 8, 8 });
+
 static void gpiomon_no_arguments(void)
 {
 	test_tool_run("gpiomon", (char *)NULL);


added PSG licensing blurb

added PSG licensing blurb

--- Modules/_elementtree.c
+++ Modules/_elementtree.c
@@ -40,6 +40,9 @@
  * http://www.pythonware.com
  */

+/* Licensed to PSF under a Contributor Agreement. */
+/* See http://www.python.org/2.4/license for licensing details. */
+
 #include "Python.h"

 #define VERSION "1.0.4"


Fix indentation from previous commit

Fix indentation from previous commit

--- Modules/_elementtree.c
+++ Modules/_elementtree.c
@@ -2339,9 +2339,9 @@
     PyObject* suri = NULL;

     if (uri)
-      suri = makestring(uri, strlen(uri));
+        suri = makestring(uri, strlen(uri));
     else
-      suri = PyString_FromStringAndSize("", 0);
+        suri = PyString_FromStringAndSize("", 0);
     if (!suri)
         return;


Add a declaration for strdup() for the Mac. (Jack)

--- Modules/parsermodule.c
+++ Modules/parsermodule.c
@@ -26,6 +26,9 @@
 					/* ISTERMINAL() / ISNONTERMINAL() */
 #include "compile.h"			/* PyNode_Compile()		  */

+#ifdef macintosh
+char *strdup Py_PROTO((char *));
+#endif

 /*  String constants used to initialize module attributes.
  *


Calculate length of AF_UNIX addr struct portably in getsockaddrarg().

--- Modules/socketmodule.c
+++ Modules/socketmodule.c
@@ -373,7 +373,7 @@
 		memcpy(addr->sun_path, path, len);
 		addr->sun_path[len] = 0;
 		*addr_ret = (struct sockaddr *) addr;
-		*len_ret = len + sizeof addr->sun_family;
+		*len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
 		return 1;
 	}
 #endif /* AF_UNIX */


Added descriptor builder functions.

Added descriptor builder functions.

--- usb/descriptor.h
+++ usb/descriptor.h
@@ -3,11 +3,23 @@

 #include <stdint.h>

+template <typename A, typename B>
+struct X {
+	A a;
+	B b;
+} __attribute__((packed));
+
+template <typename A>
+constexpr A pack(A a) {
+	return a;
+}
+
+template <typename A, typename... R>
+constexpr auto pack(A a, R... r) -> X<A, decltype(pack(r...))> {
+	return {a, pack(r...)};
+}
+
 struct Device_desc {
-	enum {
-		SIZE = 18,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint16_t bcdUSB;
@@ -24,12 +36,40 @@
 	uint8_t bNumConfigurations;
 };

+constexpr Device_desc device_desc(
+		uint16_t bcdUSB,
+		uint8_t bDeviceClass,
+		uint8_t bDeviceSubClass,
+		uint8_t bDeviceProtocol,
+		uint8_t bMaxPacketSize0,
+		uint16_t idVendor,
+		uint16_t idProduct,
+		uint16_t bcdDevice,
+		uint8_t iManufacturer,
+		uint8_t iProduct,
+		uint8_t iSerialNumber,
+		uint8_t bNumConfigurations
+	) {
+
+	return {
+		sizeof(Device_desc),
+		1,
+		bcdUSB,
+		bDeviceClass,
+		bDeviceSubClass,
+		bDeviceProtocol,
+		bMaxPacketSize0,
+		idVendor,
+		idProduct,
+		bcdDevice,
+		iManufacturer,
+		iProduct,
+		iSerialNumber,
+		bNumConfigurations
+	};
+}

 struct Configuration_desc {
-	enum {
-		SIZE = 9,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint16_t wTotalLength;
@@ -40,11 +80,29 @@
 	uint8_t bMaxPower;
 } __attribute__((packed));

+template <typename... R>
+constexpr auto configuration_desc(
+		uint8_t bNumInterfaces,
+		uint8_t bConfigurationvalue,
+		uint8_t iConfiguration,
+		uint8_t bmAttributes,
+		uint8_t bMaxPower,
+		R... r
+	) -> decltype(pack(Configuration_desc(), r...)) {
+
+	return pack(Configuration_desc {
+		sizeof(Configuration_desc),
+		2,
+		sizeof(pack(Configuration_desc(), r...)),
+		bNumInterfaces,
+		bConfigurationvalue,
+		iConfiguration,
+		bmAttributes,
+		bMaxPower
+	}, r...);
+}
+
 struct Interface_desc {
-	enum {
-		SIZE = 9,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bInterfaceNumber;
@@ -56,11 +114,32 @@
 	uint8_t iInterface;
 } __attribute__((packed));

+template <typename... R>
+constexpr auto interface_desc(
+		uint8_t bInterfaceNumber,
+		uint8_t bAlternateSetting,
+		uint8_t bNumEndpoints,
+		uint8_t bInterfaceClass,
+		uint8_t bInterfaceSubClass,
+		uint8_t bInterfaceProtocol,
+		uint8_t iInterface,
+		R... r
+	) -> decltype(pack(Interface_desc(), r...)) {
+
+	return pack(Interface_desc {
+		sizeof(Interface_desc),
+		4,
+		bInterfaceNumber,
+		bAlternateSetting,
+		bNumEndpoints,
+		bInterfaceClass,
+		bInterfaceSubClass,
+		bInterfaceProtocol,
+		iInterface
+	}, r...);
+}
+
 struct Endpoint_desc {
-	enum {
-		SIZE = 7,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bEndpointAddress;
@@ -69,22 +148,43 @@
 	uint8_t bInterval;
 } __attribute__((packed));

+constexpr Endpoint_desc endpoint_desc(
+		uint8_t bEndpointAddress,
+		uint8_t bmAttributes,
+		uint16_t wMaxPacketSize,
+		uint8_t bInterval
+	) {
+
+	return {
+		sizeof(Endpoint_desc),
+		5,
+		bEndpointAddress,
+		bmAttributes,
+		wMaxPacketSize,
+		bInterval
+	};
+}
+
 struct CDC_Header_desc {
-	enum {
-		SIZE = 5,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bDescriptorSubType;
 	uint16_t bcdCDC;
 } __attribute__((packed));

+constexpr CDC_Header_desc cdc_header_desc(
+		uint16_t bcdCDC
+	) {
+
+	return {
+		sizeof(CDC_Header_desc),
+		0x24,
+		0x00,
+		bcdCDC
+	};
+}
+
 struct CDC_Call_Management_desc {
-	enum {
-		SIZE = 5,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bDescriptorSubType;
@@ -92,22 +192,40 @@
 	uint8_t bDataInterface;
 } __attribute__((packed));

+constexpr CDC_Call_Management_desc cdc_call_management_desc(
+		uint8_t bmCapabilities,
+		uint8_t bDataInterface
+	) {
+
+	return {
+		sizeof(CDC_Call_Management_desc),
+		0x24,
+		0x01,
+		bmCapabilities,
+		bDataInterface
+	};
+}
+
 struct CDC_ACM_desc {
-	enum {
-		SIZE = 4,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bDescriptorSubType;
 	uint8_t bmCapabilities;
 } __attribute__((packed));

+constexpr CDC_ACM_desc cdc_acm_desc(
+		uint8_t bmCapabilities
+	) {
+
+	return {
+		sizeof(CDC_ACM_desc),
+		0x24,
+		0x02,
+		bmCapabilities
+	};
+}
+
 struct CDC_Union_desc {
-	enum {
-		SIZE = 5,
-	};
-
 	uint8_t bLength;
 	uint8_t bDescriptorType;
 	uint8_t bDescriptorSubType;
@@ -115,24 +233,18 @@
 	uint8_t bSubordinateInterface0;
 } __attribute__((packed));

-template <typename A, typename B>
-struct X {
-	enum {
-		SIZE = A::SIZE + B::SIZE,
-	};
-
-	A a;
-	B b;
-} __attribute__((packed));
-
-template <typename A>
-constexpr A pack(A a) {
-	return a;
-}
-
-template <typename A, typename... R>
-constexpr auto pack(A a, R... r) -> X<A, decltype(pack(r...))> {
-	return {a, pack(r...)};
+constexpr CDC_Union_desc cdc_union_desc(
+		uint8_t bControlInterface,
+		uint8_t bSubordinateInterface0
+	) {
+
+	return {
+		sizeof(CDC_Union_desc),
+		0x24,
+		0x06,
+		bControlInterface,
+		bSubordinateInterface0
+	};
 }

 #endif


use dns server supplied from uplink

use dns server supplied from uplink

--- user/user_main.c
+++ user/user_main.c
@@ -80,9 +80,10 @@
 	// stop captive dns
 	captdnsStop();

-	IP4_ADDR(&dns_ip, 8, 8, 8, 8);
-	espconn_dns_setserver(0, &dns_ip);
+#ifdef AP
+	dns_ip.addr = dns_getserver(0);
 	dhcps_set_DNS(&dns_ip);
+#endif

 #ifdef IMPULSE
 	// save sys_cfg.impulse_meter_count - in case it has been incremented since cfg_load() at boot


Initialise both TCP servers and ensure that only a single connection is handled at a time

--- user/user_main.c
+++ user/user_main.c
@@ -75,11 +75,12 @@
 	os_sprintf(rgcOutputString, "Connection dropped from port: %d\n\r", pConnection->proto.tcp->local_port);
 	os_printf(rgcOutputString);
 }
+//Recieve data from a connection
 static void ICACHE_FLASH_ATTR
 handleRecievedData(void* arg, char* pData, unsigned short iLength)
 {
 	struct espconn * pConnection = (struct espconn*) arg;
-	if(arg == &espconnCommand)
+	if(pConnection->proto.tcp->local_port == espconnCommand.proto.tcp->local_port)
 	{
 		os_sprintf(rgcOutputString, "Recieved command length recieved: %d\n\r", iLength);
 	}
@@ -139,7 +140,10 @@

 	wifi_set_opmode(0x02);

+
 	enableTCPServer(8080, &espconnCommand);
+	enableTCPServer(8081, &espconnTransfer);
+	espconn_tcp_set_max_con(1);

 	system_os_post(0,0,0);
 }


conrey_pow: fix a potential overflow issue

--- acb_dirichlet/conrey_pow.c
+++ acb_dirichlet/conrey_pow.c
@@ -16,6 +16,6 @@
 {
     ulong k;
     for (k = 0; k < G->num ; k++)
-      c->log[k] = (a->log[k]  * n) % G->P[k].phi;
+        c->log[k] = n_mulmod2(a->log[k], n, G->P[k].phi);
     c->n = nmod_pow_ui(a->n, n, G->mod);
 }