ua_types_encoding_binary.c 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "ua_util.h"
  5. #include "ua_types_encoding_binary.h"
  6. #include "ua_types_generated.h"
  7. #include "ua_types_generated_handling.h"
  8. /* Type Encoding
  9. * -------------
  10. * This file contains encoding functions for the builtin data types and generic
  11. * functions that operate on all types and arrays. This requires the type
  12. * description from a UA_DataType structure. Note that some internal (static)
  13. * deocidng functions may abort and leave the type in an inconsistent state. But
  14. * this is always handled in UA_decodeBinary, where the error is caught and the
  15. * type cleaned up.
  16. *
  17. * Breaking a message into chunks is integrated with the encoding. When the end
  18. * of a buffer is reached, a callback is executed that sends the current buffer
  19. * as a chunk and exchanges the encoding buffer "underneath" the ongoing
  20. * encoding. This enables fast sending of large messages as spurious copying is
  21. * avoided. */
  22. #if defined(__clang__)
  23. # pragma GCC diagnostic push
  24. # pragma GCC diagnostic warning "-W#warnings"
  25. #endif
  26. #ifndef UA_BINARY_OVERLAYABLE_INTEGER
  27. # warning Integer endianness could not be detected to be little endian. Use slow generic encoding.
  28. #endif
  29. /* There is no robust way to detect float endianness in clang. This warning can be removed
  30. * if the target is known to be little endian with floats in the IEEE 754 format. */
  31. #ifndef UA_BINARY_OVERLAYABLE_FLOAT
  32. # warning Float endianness could not be detected to be little endian in the IEEE 754 format. Use slow generic encoding.
  33. #endif
  34. #if defined(__clang__)
  35. # pragma GCC diagnostic pop
  36. #endif
  37. /* Jumptables for de-/encoding and computing the buffer length */
  38. typedef UA_StatusCode (*UA_encodeBinarySignature)(const void *UA_RESTRICT src, const UA_DataType *type);
  39. extern const UA_encodeBinarySignature encodeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1];
  40. typedef UA_StatusCode (*UA_decodeBinarySignature)(void *UA_RESTRICT dst, const UA_DataType *type);
  41. extern const UA_decodeBinarySignature decodeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1];
  42. typedef size_t (*UA_calcSizeBinarySignature)(const void *UA_RESTRICT p, const UA_DataType *contenttype);
  43. extern const UA_calcSizeBinarySignature calcSizeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1];
  44. /* Pointer to custom datatypes in the server or client. Set inside
  45. * UA_decodeBinary */
  46. UA_THREAD_LOCAL size_t customTypesArraySize;
  47. UA_THREAD_LOCAL const UA_DataType *customTypesArray;
  48. /* Pointers to the current position and the last position in the buffer */
  49. UA_THREAD_LOCAL UA_Byte *pos;
  50. UA_THREAD_LOCAL const UA_Byte *end;
  51. /* In UA_encodeBinaryInternal, we store a pointer to the last "good" position in
  52. * the buffer. When encoding reaches the end of the buffer, send out a chunk
  53. * until that position, replace the buffer and retry encoding after the last
  54. * "checkpoint". The status code UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED is used
  55. * exclusively to indicate that the end of the buffer was reached.
  56. *
  57. * In order to prevent restoring to an old buffer position (where the buffer was
  58. * exchanged within a call from UA_encodeBinaryInternal and is no longer
  59. * valied), no methods must return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED after
  60. * calling exchangeBuffer(). This needs to be ensured for the following methods:
  61. *
  62. * UA_encodeBinaryInternal
  63. * Array_encodeBinary
  64. * NodeId_encodeBinary
  65. * ExpandedNodeId_encodeBinary
  66. * LocalizedText_encodeBinary
  67. * ExtensionObject_encodeBinary
  68. * Variant_encodeBinary
  69. * DataValue_encodeBinary
  70. * DiagnosticInfo_encodeBinary */
  71. /* Thread-local buffers used for exchanging the buffer for chunking */
  72. UA_THREAD_LOCAL UA_exchangeEncodeBuffer exchangeBufferCallback;
  73. UA_THREAD_LOCAL void *exchangeBufferCallbackHandle;
  74. /* Send the current chunk and replace the buffer */
  75. static UA_StatusCode
  76. exchangeBuffer(void) {
  77. if(!exchangeBufferCallback)
  78. return UA_STATUSCODE_BADENCODINGERROR;
  79. /* Store context variables since exchangeBuffer might call UA_encode itself */
  80. UA_exchangeEncodeBuffer store_exchangeBufferCallback = exchangeBufferCallback;
  81. void *store_exchangeBufferCallbackHandle = exchangeBufferCallbackHandle;
  82. UA_StatusCode retval = exchangeBufferCallback(exchangeBufferCallbackHandle, &pos, &end);
  83. /* Restore context variables */
  84. exchangeBufferCallback = store_exchangeBufferCallback;
  85. exchangeBufferCallbackHandle = store_exchangeBufferCallbackHandle;
  86. return retval;
  87. }
  88. /*****************/
  89. /* Integer Types */
  90. /*****************/
  91. #if !UA_BINARY_OVERLAYABLE_INTEGER
  92. /* These en/decoding functions are only used when the architecture isn't little-endian. */
  93. static void
  94. UA_encode16(const UA_UInt16 v, UA_Byte buf[2]) {
  95. buf[0] = (UA_Byte)v;
  96. buf[1] = (UA_Byte)(v >> 8);
  97. }
  98. static void
  99. UA_decode16(const UA_Byte buf[2], UA_UInt16 *v) {
  100. *v = (UA_UInt16)((UA_UInt16)buf[0] + (((UA_UInt16)buf[1]) << 8));
  101. }
  102. static void
  103. UA_encode32(const UA_UInt32 v, UA_Byte buf[4]) {
  104. buf[0] = (UA_Byte)v;
  105. buf[1] = (UA_Byte)(v >> 8);
  106. buf[2] = (UA_Byte)(v >> 16);
  107. buf[3] = (UA_Byte)(v >> 24);
  108. }
  109. static void
  110. UA_decode32(const UA_Byte buf[4], UA_UInt32 *v) {
  111. *v = (UA_UInt32)((UA_UInt32)buf[0] +
  112. (((UA_UInt32)buf[1]) << 8) +
  113. (((UA_UInt32)buf[2]) << 16) +
  114. (((UA_UInt32)buf[3]) << 24));
  115. }
  116. static void
  117. UA_encode64(const UA_UInt64 v, UA_Byte buf[8]) {
  118. buf[0] = (UA_Byte)v;
  119. buf[1] = (UA_Byte)(v >> 8);
  120. buf[2] = (UA_Byte)(v >> 16);
  121. buf[3] = (UA_Byte)(v >> 24);
  122. buf[4] = (UA_Byte)(v >> 32);
  123. buf[5] = (UA_Byte)(v >> 40);
  124. buf[6] = (UA_Byte)(v >> 48);
  125. buf[7] = (UA_Byte)(v >> 56);
  126. }
  127. static void
  128. UA_decode64(const UA_Byte buf[8], UA_UInt64 *v) {
  129. *v = (UA_UInt64)((UA_UInt64)buf[0] +
  130. (((UA_UInt64)buf[1]) << 8) +
  131. (((UA_UInt64)buf[2]) << 16) +
  132. (((UA_UInt64)buf[3]) << 24) +
  133. (((UA_UInt64)buf[4]) << 32) +
  134. (((UA_UInt64)buf[5]) << 40) +
  135. (((UA_UInt64)buf[6]) << 48) +
  136. (((UA_UInt64)buf[7]) << 56));
  137. }
  138. #endif /* !UA_BINARY_OVERLAYABLE_INTEGER */
  139. /* Boolean */
  140. static UA_StatusCode
  141. Boolean_encodeBinary(const UA_Boolean *src, const UA_DataType *_) {
  142. if(pos + sizeof(UA_Boolean) > end)
  143. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  144. *pos = *(const UA_Byte*)src;
  145. ++pos;
  146. return UA_STATUSCODE_GOOD;
  147. }
  148. static UA_StatusCode
  149. Boolean_decodeBinary(UA_Boolean *dst, const UA_DataType *_) {
  150. if(pos + sizeof(UA_Boolean) > end)
  151. return UA_STATUSCODE_BADDECODINGERROR;
  152. *dst = (*pos > 0) ? true : false;
  153. ++pos;
  154. return UA_STATUSCODE_GOOD;
  155. }
  156. /* Byte */
  157. static UA_StatusCode
  158. Byte_encodeBinary(const UA_Byte *src, const UA_DataType *_) {
  159. if(pos + sizeof(UA_Byte) > end)
  160. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  161. *pos = *(const UA_Byte*)src;
  162. ++pos;
  163. return UA_STATUSCODE_GOOD;
  164. }
  165. static UA_StatusCode
  166. Byte_decodeBinary(UA_Byte *dst, const UA_DataType *_) {
  167. if(pos + sizeof(UA_Byte) > end)
  168. return UA_STATUSCODE_BADDECODINGERROR;
  169. *dst = *pos;
  170. ++pos;
  171. return UA_STATUSCODE_GOOD;
  172. }
  173. /* UInt16 */
  174. static UA_StatusCode
  175. UInt16_encodeBinary(UA_UInt16 const *src, const UA_DataType *_) {
  176. if(pos + sizeof(UA_UInt16) > end)
  177. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  178. #if UA_BINARY_OVERLAYABLE_INTEGER
  179. memcpy(pos, src, sizeof(UA_UInt16));
  180. #else
  181. UA_encode16(*src, pos);
  182. #endif
  183. pos += 2;
  184. return UA_STATUSCODE_GOOD;
  185. }
  186. static UA_INLINE UA_StatusCode
  187. Int16_encodeBinary(UA_Int16 const *src, const UA_DataType *_) {
  188. return UInt16_encodeBinary((const UA_UInt16*)src, NULL);
  189. }
  190. static UA_StatusCode
  191. UInt16_decodeBinary(UA_UInt16 *dst, const UA_DataType *_) {
  192. if(pos + sizeof(UA_UInt16) > end)
  193. return UA_STATUSCODE_BADDECODINGERROR;
  194. #if UA_BINARY_OVERLAYABLE_INTEGER
  195. memcpy(dst, pos, sizeof(UA_UInt16));
  196. #else
  197. UA_decode16(pos, dst);
  198. #endif
  199. pos += 2;
  200. return UA_STATUSCODE_GOOD;
  201. }
  202. static UA_INLINE UA_StatusCode
  203. Int16_decodeBinary(UA_Int16 *dst) {
  204. return UInt16_decodeBinary((UA_UInt16*)dst, NULL);
  205. }
  206. /* UInt32 */
  207. static UA_StatusCode
  208. UInt32_encodeBinary(UA_UInt32 const *src, const UA_DataType *_) {
  209. if(pos + sizeof(UA_UInt32) > end)
  210. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  211. #if UA_BINARY_OVERLAYABLE_INTEGER
  212. memcpy(pos, src, sizeof(UA_UInt32));
  213. #else
  214. UA_encode32(*src, pos);
  215. #endif
  216. pos += 4;
  217. return UA_STATUSCODE_GOOD;
  218. }
  219. static UA_INLINE UA_StatusCode
  220. Int32_encodeBinary(UA_Int32 const *src) {
  221. return UInt32_encodeBinary((const UA_UInt32*)src, NULL);
  222. }
  223. static UA_INLINE UA_StatusCode
  224. StatusCode_encodeBinary(UA_StatusCode const *src) {
  225. return UInt32_encodeBinary((const UA_UInt32*)src, NULL);
  226. }
  227. static UA_StatusCode
  228. UInt32_decodeBinary(UA_UInt32 *dst, const UA_DataType *_) {
  229. if(pos + sizeof(UA_UInt32) > end)
  230. return UA_STATUSCODE_BADDECODINGERROR;
  231. #if UA_BINARY_OVERLAYABLE_INTEGER
  232. memcpy(dst, pos, sizeof(UA_UInt32));
  233. #else
  234. UA_decode32(pos, dst);
  235. #endif
  236. pos += 4;
  237. return UA_STATUSCODE_GOOD;
  238. }
  239. static UA_INLINE UA_StatusCode
  240. Int32_decodeBinary(UA_Int32 *dst) {
  241. return UInt32_decodeBinary((UA_UInt32*)dst, NULL);
  242. }
  243. static UA_INLINE UA_StatusCode
  244. StatusCode_decodeBinary(UA_StatusCode *dst) {
  245. return UInt32_decodeBinary((UA_UInt32*)dst, NULL);
  246. }
  247. /* UInt64 */
  248. static UA_StatusCode
  249. UInt64_encodeBinary(UA_UInt64 const *src, const UA_DataType *_) {
  250. if(pos + sizeof(UA_UInt64) > end)
  251. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  252. #if UA_BINARY_OVERLAYABLE_INTEGER
  253. memcpy(pos, src, sizeof(UA_UInt64));
  254. #else
  255. UA_encode64(*src, pos);
  256. #endif
  257. pos += 8;
  258. return UA_STATUSCODE_GOOD;
  259. }
  260. static UA_INLINE UA_StatusCode
  261. Int64_encodeBinary(UA_Int64 const *src) {
  262. return UInt64_encodeBinary((const UA_UInt64*)src, NULL);
  263. }
  264. static UA_INLINE UA_StatusCode
  265. DateTime_encodeBinary(UA_DateTime const *src) {
  266. return UInt64_encodeBinary((const UA_UInt64*)src, NULL);
  267. }
  268. static UA_StatusCode
  269. UInt64_decodeBinary(UA_UInt64 *dst, const UA_DataType *_) {
  270. if(pos + sizeof(UA_UInt64) > end)
  271. return UA_STATUSCODE_BADDECODINGERROR;
  272. #if UA_BINARY_OVERLAYABLE_INTEGER
  273. memcpy(dst, pos, sizeof(UA_UInt64));
  274. #else
  275. UA_decode64(pos, dst);
  276. #endif
  277. pos += 8;
  278. return UA_STATUSCODE_GOOD;
  279. }
  280. static UA_INLINE UA_StatusCode
  281. Int64_decodeBinary(UA_Int64 *dst) {
  282. return UInt64_decodeBinary((UA_UInt64*)dst, NULL);
  283. }
  284. static UA_INLINE UA_StatusCode
  285. DateTime_decodeBinary(UA_DateTime *dst) {
  286. return UInt64_decodeBinary((UA_UInt64*)dst, NULL);
  287. }
  288. /************************/
  289. /* Floating Point Types */
  290. /************************/
  291. #if UA_BINARY_OVERLAYABLE_FLOAT
  292. # define Float_encodeBinary UInt32_encodeBinary
  293. # define Float_decodeBinary UInt32_decodeBinary
  294. # define Double_encodeBinary UInt64_encodeBinary
  295. # define Double_decodeBinary UInt64_decodeBinary
  296. #else
  297. #include <math.h>
  298. /* Handling of IEEE754 floating point values was taken from Beej's Guide to
  299. * Network Programming (http://beej.us/guide/bgnet/) and enhanced to cover the
  300. * edge cases +/-0, +/-inf and nan. */
  301. static uint64_t
  302. pack754(long double f, unsigned bits, unsigned expbits) {
  303. unsigned significandbits = bits - expbits - 1;
  304. long double fnorm;
  305. long long sign;
  306. if (f < 0) { sign = 1; fnorm = -f; }
  307. else { sign = 0; fnorm = f; }
  308. int shift = 0;
  309. while(fnorm >= 2.0) { fnorm /= 2.0; ++shift; }
  310. while(fnorm < 1.0) { fnorm *= 2.0; --shift; }
  311. fnorm = fnorm - 1.0;
  312. long long significand = (long long)(fnorm * ((float)(1LL<<significandbits) + 0.5f));
  313. long long exponent = shift + ((1<<(expbits-1)) - 1);
  314. return (uint64_t)((sign<<(bits-1)) | (exponent<<(bits-expbits-1)) | significand);
  315. }
  316. static long double
  317. unpack754(uint64_t i, unsigned bits, unsigned expbits) {
  318. unsigned significandbits = bits - expbits - 1;
  319. long double result = (long double)(i&(uint64_t)((1LL<<significandbits)-1));
  320. result /= (1LL<<significandbits);
  321. result += 1.0f;
  322. unsigned bias = (unsigned)(1<<(expbits-1)) - 1;
  323. long long shift = (long long)((i>>significandbits) & (uint64_t)((1LL<<expbits)-1)) - bias;
  324. while(shift > 0) { result *= 2.0; --shift; }
  325. while(shift < 0) { result /= 2.0; ++shift; }
  326. result *= ((i>>(bits-1))&1)? -1.0: 1.0;
  327. return result;
  328. }
  329. /* Float */
  330. #define FLOAT_NAN 0xffc00000
  331. #define FLOAT_INF 0x7f800000
  332. #define FLOAT_NEG_INF 0xff800000
  333. #define FLOAT_NEG_ZERO 0x80000000
  334. static UA_StatusCode
  335. Float_encodeBinary(UA_Float const *src, const UA_DataType *_) {
  336. UA_Float f = *src;
  337. UA_UInt32 encoded;
  338. //cppcheck-suppress duplicateExpression
  339. if(f != f) encoded = FLOAT_NAN;
  340. else if(f == 0.0f) encoded = signbit(f) ? FLOAT_NEG_ZERO : 0;
  341. //cppcheck-suppress duplicateExpression
  342. else if(f/f != f/f) encoded = f > 0 ? FLOAT_INF : FLOAT_NEG_INF;
  343. else encoded = (UA_UInt32)pack754(f, 32, 8);
  344. return UInt32_encodeBinary(&encoded, NULL);
  345. }
  346. static UA_StatusCode
  347. Float_decodeBinary(UA_Float *dst, const UA_DataType *_) {
  348. UA_UInt32 decoded;
  349. UA_StatusCode retval = UInt32_decodeBinary(&decoded, NULL);
  350. if(retval != UA_STATUSCODE_GOOD)
  351. return retval;
  352. if(decoded == 0) *dst = 0.0f;
  353. else if(decoded == FLOAT_NEG_ZERO) *dst = -0.0f;
  354. else if(decoded == FLOAT_INF) *dst = INFINITY;
  355. else if(decoded == FLOAT_NEG_INF) *dst = -INFINITY;
  356. if((decoded >= 0x7f800001 && decoded <= 0x7fffffff) ||
  357. (decoded >= 0xff800001 && decoded <= 0xffffffff)) *dst = NAN;
  358. else *dst = (UA_Float)unpack754(decoded, 32, 8);
  359. return UA_STATUSCODE_GOOD;
  360. }
  361. /* Double */
  362. #define DOUBLE_NAN 0xfff8000000000000L
  363. #define DOUBLE_INF 0x7ff0000000000000L
  364. #define DOUBLE_NEG_INF 0xfff0000000000000L
  365. #define DOUBLE_NEG_ZERO 0x8000000000000000L
  366. static UA_StatusCode
  367. Double_encodeBinary(UA_Double const *src, const UA_DataType *_) {
  368. UA_Double d = *src;
  369. UA_UInt64 encoded;
  370. //cppcheck-suppress duplicateExpression
  371. if(d != d) encoded = DOUBLE_NAN;
  372. else if(d == 0.0) encoded = signbit(d) ? DOUBLE_NEG_ZERO : 0;
  373. //cppcheck-suppress duplicateExpression
  374. else if(d/d != d/d) encoded = d > 0 ? DOUBLE_INF : DOUBLE_NEG_INF;
  375. else encoded = pack754(d, 64, 11);
  376. return UInt64_encodeBinary(&encoded, NULL);
  377. }
  378. static UA_StatusCode
  379. Double_decodeBinary(UA_Double *dst, const UA_DataType *_) {
  380. UA_UInt64 decoded;
  381. UA_StatusCode retval = UInt64_decodeBinary(&decoded, NULL);
  382. if(retval != UA_STATUSCODE_GOOD)
  383. return retval;
  384. if(decoded == 0) *dst = 0.0;
  385. else if(decoded == DOUBLE_NEG_ZERO) *dst = -0.0;
  386. else if(decoded == DOUBLE_INF) *dst = INFINITY;
  387. else if(decoded == DOUBLE_NEG_INF) *dst = -INFINITY;
  388. //cppcheck-suppress redundantCondition
  389. if((decoded >= 0x7ff0000000000001L && decoded <= 0x7fffffffffffffffL) ||
  390. (decoded >= 0xfff0000000000001L && decoded <= 0xffffffffffffffffL)) *dst = NAN;
  391. else *dst = (UA_Double)unpack754(decoded, 64, 11);
  392. return UA_STATUSCODE_GOOD;
  393. }
  394. #endif
  395. /* If encoding fails, exchange the buffer and try again. It is assumed that
  396. * encoding of numerical types never fails on a fresh buffer. */
  397. static UA_StatusCode
  398. encodeNumericWithExchangeBuffer(const void *ptr,
  399. UA_encodeBinarySignature encodeFunc) {
  400. UA_StatusCode retval = encodeFunc(ptr, NULL);
  401. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED) {
  402. retval = exchangeBuffer();
  403. if(retval != UA_STATUSCODE_GOOD)
  404. return retval;
  405. encodeFunc(ptr, NULL);
  406. }
  407. return UA_STATUSCODE_GOOD;
  408. }
  409. /* If the type is more complex, wrap encoding into the following method to
  410. * ensure that the buffer is exchanged with intermediate checkpoints. */
  411. static UA_StatusCode
  412. UA_encodeBinaryInternal(const void *src, const UA_DataType *type);
  413. /******************/
  414. /* Array Handling */
  415. /******************/
  416. static UA_StatusCode
  417. Array_encodeBinaryOverlayable(uintptr_t ptr, size_t length, size_t elementMemSize) {
  418. /* Store the number of already encoded elements */
  419. size_t finished = 0;
  420. /* Loop as long as more elements remain than fit into the chunk */
  421. while(end < pos + (elementMemSize * (length-finished))) {
  422. size_t possible = ((uintptr_t)end - (uintptr_t)pos) / (sizeof(UA_Byte) * elementMemSize);
  423. size_t possibleMem = possible * elementMemSize;
  424. memcpy(pos, (void*)ptr, possibleMem);
  425. pos += possibleMem;
  426. ptr += possibleMem;
  427. finished += possible;
  428. UA_StatusCode retval = exchangeBuffer();
  429. if(retval != UA_STATUSCODE_GOOD)
  430. return retval;
  431. }
  432. /* Encode the remaining elements */
  433. memcpy(pos, (void*)ptr, elementMemSize * (length-finished));
  434. pos += elementMemSize * (length-finished);
  435. return UA_STATUSCODE_GOOD;
  436. }
  437. static UA_StatusCode
  438. Array_encodeBinaryComplex(uintptr_t ptr, size_t length, const UA_DataType *type) {
  439. /* Get the encoding function for the data type. The jumptable at
  440. * UA_BUILTIN_TYPES_COUNT points to the generic UA_encodeBinary method */
  441. size_t encode_index = type->builtin ? type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  442. UA_encodeBinarySignature encodeType = encodeBinaryJumpTable[encode_index];
  443. /* Encode every element */
  444. for(size_t i = 0; i < length; ++i) {
  445. UA_Byte *oldpos = pos;
  446. UA_StatusCode retval = encodeType((const void*)ptr, type);
  447. ptr += type->memSize;
  448. /* Encoding failed, switch to the next chunk when possible */
  449. if(retval != UA_STATUSCODE_GOOD) {
  450. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED) {
  451. pos = oldpos; /* Set buffer position to the end of the last encoded element */
  452. retval = exchangeBuffer();
  453. ptr -= type->memSize; /* Undo to retry encoding the ith element */
  454. --i;
  455. }
  456. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  457. if(retval != UA_STATUSCODE_GOOD)
  458. return retval; /* Unrecoverable fail */
  459. }
  460. }
  461. return UA_STATUSCODE_GOOD;
  462. }
  463. static UA_StatusCode
  464. Array_encodeBinary(const void *src, size_t length, const UA_DataType *type) {
  465. /* Check and convert the array length to int32 */
  466. UA_Int32 signed_length = -1;
  467. if(length > UA_INT32_MAX)
  468. return UA_STATUSCODE_BADINTERNALERROR;
  469. if(length > 0)
  470. signed_length = (UA_Int32)length;
  471. else if(src == UA_EMPTY_ARRAY_SENTINEL)
  472. signed_length = 0;
  473. /* Encode the array length */
  474. UA_StatusCode retval =
  475. encodeNumericWithExchangeBuffer(&signed_length,
  476. (UA_encodeBinarySignature)UInt32_encodeBinary);
  477. /* Quit early? */
  478. if(retval != UA_STATUSCODE_GOOD || length == 0)
  479. return retval;
  480. /* Encode the content */
  481. if(!type->overlayable)
  482. return Array_encodeBinaryComplex((uintptr_t)src, length, type);
  483. return Array_encodeBinaryOverlayable((uintptr_t)src, length, type->memSize);
  484. }
  485. static UA_StatusCode
  486. Array_decodeBinary(void *UA_RESTRICT *UA_RESTRICT dst,
  487. size_t *out_length, const UA_DataType *type) {
  488. /* Decode the length */
  489. UA_Int32 signed_length;
  490. UA_StatusCode retval = Int32_decodeBinary(&signed_length);
  491. if(retval != UA_STATUSCODE_GOOD)
  492. return retval;
  493. /* Return early for empty arrays */
  494. if(signed_length <= 0) {
  495. *out_length = 0;
  496. if(signed_length < 0)
  497. *dst = NULL;
  498. else
  499. *dst = UA_EMPTY_ARRAY_SENTINEL;
  500. return UA_STATUSCODE_GOOD;
  501. }
  502. /* Filter out arrays that can obviously not be decoded, because the message
  503. * is too small for the array length. This prevents the allocation of very
  504. * long arrays for bogus messages.*/
  505. size_t length = (size_t)signed_length;
  506. if(pos + ((type->memSize * length) / 32) > end)
  507. return UA_STATUSCODE_BADDECODINGERROR;
  508. /* Allocate memory */
  509. *dst = UA_calloc(length, type->memSize);
  510. if(!*dst)
  511. return UA_STATUSCODE_BADOUTOFMEMORY;
  512. if(type->overlayable) {
  513. /* memcpy overlayable array */
  514. if(end < pos + (type->memSize * length)) {
  515. UA_free(*dst);
  516. *dst = NULL;
  517. return UA_STATUSCODE_BADDECODINGERROR;
  518. }
  519. memcpy(*dst, pos, type->memSize * length);
  520. pos += type->memSize * length;
  521. } else {
  522. /* Decode array members */
  523. uintptr_t ptr = (uintptr_t)*dst;
  524. size_t decode_index = type->builtin ? type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  525. for(size_t i = 0; i < length; ++i) {
  526. retval = decodeBinaryJumpTable[decode_index]((void*)ptr, type);
  527. if(retval != UA_STATUSCODE_GOOD) {
  528. UA_Array_delete(*dst, i, type);
  529. *dst = NULL;
  530. return retval;
  531. }
  532. ptr += type->memSize;
  533. }
  534. }
  535. *out_length = length;
  536. return UA_STATUSCODE_GOOD;
  537. }
  538. /*****************/
  539. /* Builtin Types */
  540. /*****************/
  541. static UA_StatusCode
  542. String_encodeBinary(UA_String const *src, const UA_DataType *_) {
  543. return Array_encodeBinary(src->data, src->length, &UA_TYPES[UA_TYPES_BYTE]);
  544. }
  545. static UA_StatusCode
  546. String_decodeBinary(UA_String *dst, const UA_DataType *_) {
  547. return Array_decodeBinary((void**)&dst->data, &dst->length, &UA_TYPES[UA_TYPES_BYTE]);
  548. }
  549. static UA_INLINE UA_StatusCode
  550. ByteString_encodeBinary(UA_ByteString const *src) {
  551. return String_encodeBinary((const UA_String*)src, NULL);
  552. }
  553. static UA_INLINE UA_StatusCode
  554. ByteString_decodeBinary(UA_ByteString *dst) {
  555. return String_decodeBinary((UA_ByteString*)dst, NULL);
  556. }
  557. /* Guid */
  558. static UA_StatusCode
  559. Guid_encodeBinary(UA_Guid const *src, const UA_DataType *_) {
  560. UA_StatusCode retval = UInt32_encodeBinary(&src->data1, NULL);
  561. retval |= UInt16_encodeBinary(&src->data2, NULL);
  562. retval |= UInt16_encodeBinary(&src->data3, NULL);
  563. if(pos + (8*sizeof(UA_Byte)) > end)
  564. return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
  565. memcpy(pos, src->data4, 8*sizeof(UA_Byte));
  566. pos += 8;
  567. return retval;
  568. }
  569. static UA_StatusCode
  570. Guid_decodeBinary(UA_Guid *dst, const UA_DataType *_) {
  571. UA_StatusCode retval = UInt32_decodeBinary(&dst->data1, NULL);
  572. retval |= UInt16_decodeBinary(&dst->data2, NULL);
  573. retval |= UInt16_decodeBinary(&dst->data3, NULL);
  574. if(pos + (8*sizeof(UA_Byte)) > end)
  575. return UA_STATUSCODE_BADDECODINGERROR;
  576. memcpy(dst->data4, pos, 8*sizeof(UA_Byte));
  577. pos += 8;
  578. return retval;
  579. }
  580. /* NodeId */
  581. #define UA_NODEIDTYPE_NUMERIC_TWOBYTE 0
  582. #define UA_NODEIDTYPE_NUMERIC_FOURBYTE 1
  583. #define UA_NODEIDTYPE_NUMERIC_COMPLETE 2
  584. /* For ExpandedNodeId, we prefill the encoding mask. We can return
  585. * UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED before encoding the string, as the
  586. * buffer is not replaced. */
  587. static UA_StatusCode
  588. NodeId_encodeBinaryWithEncodingMask(UA_NodeId const *src, UA_Byte encoding) {
  589. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  590. switch(src->identifierType) {
  591. case UA_NODEIDTYPE_NUMERIC:
  592. if(src->identifier.numeric > UA_UINT16_MAX || src->namespaceIndex > UA_BYTE_MAX) {
  593. encoding |= UA_NODEIDTYPE_NUMERIC_COMPLETE;
  594. retval |= Byte_encodeBinary(&encoding, NULL);
  595. retval |= UInt16_encodeBinary(&src->namespaceIndex, NULL);
  596. retval |= UInt32_encodeBinary(&src->identifier.numeric, NULL);
  597. } else if(src->identifier.numeric > UA_BYTE_MAX || src->namespaceIndex > 0) {
  598. encoding |= UA_NODEIDTYPE_NUMERIC_FOURBYTE;
  599. retval |= Byte_encodeBinary(&encoding, NULL);
  600. UA_Byte nsindex = (UA_Byte)src->namespaceIndex;
  601. retval |= Byte_encodeBinary(&nsindex, NULL);
  602. UA_UInt16 identifier16 = (UA_UInt16)src->identifier.numeric;
  603. retval |= UInt16_encodeBinary(&identifier16, NULL);
  604. } else {
  605. encoding |= UA_NODEIDTYPE_NUMERIC_TWOBYTE;
  606. retval |= Byte_encodeBinary(&encoding, NULL);
  607. UA_Byte identifier8 = (UA_Byte)src->identifier.numeric;
  608. retval |= Byte_encodeBinary(&identifier8, NULL);
  609. }
  610. break;
  611. case UA_NODEIDTYPE_STRING:
  612. encoding |= UA_NODEIDTYPE_STRING;
  613. retval |= Byte_encodeBinary(&encoding, NULL);
  614. retval |= UInt16_encodeBinary(&src->namespaceIndex, NULL);
  615. if(retval != UA_STATUSCODE_GOOD)
  616. return retval;
  617. retval = String_encodeBinary(&src->identifier.string, NULL);
  618. break;
  619. case UA_NODEIDTYPE_GUID:
  620. encoding |= UA_NODEIDTYPE_GUID;
  621. retval |= Byte_encodeBinary(&encoding, NULL);
  622. retval |= UInt16_encodeBinary(&src->namespaceIndex, NULL);
  623. retval |= Guid_encodeBinary(&src->identifier.guid, NULL);
  624. break;
  625. case UA_NODEIDTYPE_BYTESTRING:
  626. encoding |= UA_NODEIDTYPE_BYTESTRING;
  627. retval |= Byte_encodeBinary(&encoding, NULL);
  628. retval |= UInt16_encodeBinary(&src->namespaceIndex, NULL);
  629. if(retval != UA_STATUSCODE_GOOD)
  630. return retval;
  631. retval = ByteString_encodeBinary(&src->identifier.byteString);
  632. break;
  633. default:
  634. return UA_STATUSCODE_BADINTERNALERROR;
  635. }
  636. return retval;
  637. }
  638. static UA_StatusCode
  639. NodeId_encodeBinary(UA_NodeId const *src, const UA_DataType *_) {
  640. return NodeId_encodeBinaryWithEncodingMask(src, 0);
  641. }
  642. static UA_StatusCode
  643. NodeId_decodeBinary(UA_NodeId *dst, const UA_DataType *_) {
  644. UA_Byte dstByte = 0, encodingByte = 0;
  645. UA_UInt16 dstUInt16 = 0;
  646. UA_StatusCode retval = Byte_decodeBinary(&encodingByte, NULL);
  647. if(retval != UA_STATUSCODE_GOOD)
  648. return retval;
  649. switch (encodingByte) {
  650. case UA_NODEIDTYPE_NUMERIC_TWOBYTE:
  651. dst->identifierType = UA_NODEIDTYPE_NUMERIC;
  652. retval = Byte_decodeBinary(&dstByte, NULL);
  653. dst->identifier.numeric = dstByte;
  654. dst->namespaceIndex = 0;
  655. break;
  656. case UA_NODEIDTYPE_NUMERIC_FOURBYTE:
  657. dst->identifierType = UA_NODEIDTYPE_NUMERIC;
  658. retval |= Byte_decodeBinary(&dstByte, NULL);
  659. dst->namespaceIndex = dstByte;
  660. retval |= UInt16_decodeBinary(&dstUInt16, NULL);
  661. dst->identifier.numeric = dstUInt16;
  662. break;
  663. case UA_NODEIDTYPE_NUMERIC_COMPLETE:
  664. dst->identifierType = UA_NODEIDTYPE_NUMERIC;
  665. retval |= UInt16_decodeBinary(&dst->namespaceIndex, NULL);
  666. retval |= UInt32_decodeBinary(&dst->identifier.numeric, NULL);
  667. break;
  668. case UA_NODEIDTYPE_STRING:
  669. dst->identifierType = UA_NODEIDTYPE_STRING;
  670. retval |= UInt16_decodeBinary(&dst->namespaceIndex, NULL);
  671. retval |= String_decodeBinary(&dst->identifier.string, NULL);
  672. break;
  673. case UA_NODEIDTYPE_GUID:
  674. dst->identifierType = UA_NODEIDTYPE_GUID;
  675. retval |= UInt16_decodeBinary(&dst->namespaceIndex, NULL);
  676. retval |= Guid_decodeBinary(&dst->identifier.guid, NULL);
  677. break;
  678. case UA_NODEIDTYPE_BYTESTRING:
  679. dst->identifierType = UA_NODEIDTYPE_BYTESTRING;
  680. retval |= UInt16_decodeBinary(&dst->namespaceIndex, NULL);
  681. retval |= ByteString_decodeBinary(&dst->identifier.byteString);
  682. break;
  683. default:
  684. retval |= UA_STATUSCODE_BADINTERNALERROR;
  685. break;
  686. }
  687. return retval;
  688. }
  689. /* ExpandedNodeId */
  690. #define UA_EXPANDEDNODEID_NAMESPACEURI_FLAG 0x80
  691. #define UA_EXPANDEDNODEID_SERVERINDEX_FLAG 0x40
  692. static UA_StatusCode
  693. ExpandedNodeId_encodeBinary(UA_ExpandedNodeId const *src, const UA_DataType *_) {
  694. /* Set up the encoding mask */
  695. UA_Byte encoding = 0;
  696. if((void*)src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL)
  697. encoding |= UA_EXPANDEDNODEID_NAMESPACEURI_FLAG;
  698. if(src->serverIndex > 0)
  699. encoding |= UA_EXPANDEDNODEID_SERVERINDEX_FLAG;
  700. /* Encode the NodeId */
  701. UA_StatusCode retval = NodeId_encodeBinaryWithEncodingMask(&src->nodeId, encoding);
  702. if(retval != UA_STATUSCODE_GOOD)
  703. return retval;
  704. /* Encode the namespace. Do not return
  705. * UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED afterwards. */
  706. if((void*)src->namespaceUri.data > UA_EMPTY_ARRAY_SENTINEL) {
  707. retval = String_encodeBinary(&src->namespaceUri, NULL);
  708. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  709. if(retval != UA_STATUSCODE_GOOD)
  710. return retval;
  711. }
  712. /* Encode the serverIndex */
  713. if(src->serverIndex > 0)
  714. retval = encodeNumericWithExchangeBuffer(&src->serverIndex,
  715. (UA_encodeBinarySignature)UInt32_encodeBinary);
  716. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  717. return retval;
  718. }
  719. static UA_StatusCode
  720. ExpandedNodeId_decodeBinary(UA_ExpandedNodeId *dst, const UA_DataType *_) {
  721. /* Decode the encoding mask */
  722. if(pos >= end)
  723. return UA_STATUSCODE_BADDECODINGERROR;
  724. UA_Byte encoding = *pos;
  725. /* Mask out the encoding byte on the stream to decode the NodeId only */
  726. *pos = encoding & (UA_Byte)~(UA_EXPANDEDNODEID_NAMESPACEURI_FLAG |
  727. UA_EXPANDEDNODEID_SERVERINDEX_FLAG);
  728. UA_StatusCode retval = NodeId_decodeBinary(&dst->nodeId, NULL);
  729. /* Decode the NamespaceUri */
  730. if(encoding & UA_EXPANDEDNODEID_NAMESPACEURI_FLAG) {
  731. dst->nodeId.namespaceIndex = 0;
  732. retval |= String_decodeBinary(&dst->namespaceUri, NULL);
  733. }
  734. /* Decode the ServerIndex */
  735. if(encoding & UA_EXPANDEDNODEID_SERVERINDEX_FLAG)
  736. retval |= UInt32_decodeBinary(&dst->serverIndex, NULL);
  737. return retval;
  738. }
  739. /* LocalizedText */
  740. #define UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_LOCALE 0x01
  741. #define UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_TEXT 0x02
  742. static UA_StatusCode
  743. LocalizedText_encodeBinary(UA_LocalizedText const *src, const UA_DataType *_) {
  744. /* Set up the encoding mask */
  745. UA_Byte encoding = 0;
  746. if(src->locale.data)
  747. encoding |= UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_LOCALE;
  748. if(src->text.data)
  749. encoding |= UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_TEXT;
  750. /* Encode the encoding byte */
  751. UA_StatusCode retval = Byte_encodeBinary(&encoding, NULL);
  752. if(retval != UA_STATUSCODE_GOOD)
  753. return retval;
  754. /* Encode the strings */
  755. if(encoding & UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_LOCALE)
  756. retval |= String_encodeBinary(&src->locale, NULL);
  757. if(encoding & UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_TEXT)
  758. retval |= String_encodeBinary(&src->text, NULL);
  759. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  760. return retval;
  761. }
  762. static UA_StatusCode
  763. LocalizedText_decodeBinary(UA_LocalizedText *dst, const UA_DataType *_) {
  764. /* Decode the encoding mask */
  765. UA_Byte encoding = 0;
  766. UA_StatusCode retval = Byte_decodeBinary(&encoding, NULL);
  767. /* Decode the content */
  768. if(encoding & UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_LOCALE)
  769. retval |= String_decodeBinary(&dst->locale, NULL);
  770. if(encoding & UA_LOCALIZEDTEXT_ENCODINGMASKTYPE_TEXT)
  771. retval |= String_decodeBinary(&dst->text, NULL);
  772. return retval;
  773. }
  774. /* The binary encoding has a different nodeid from the data type. So it is not
  775. * possible to reuse UA_findDataType */
  776. static const UA_DataType *
  777. findDataTypeByBinary(const UA_NodeId *typeId) {
  778. /* We only store a numeric identifier for the encoding nodeid of data types */
  779. if(typeId->identifierType != UA_NODEIDTYPE_NUMERIC)
  780. return NULL;
  781. /* Custom or standard data type? */
  782. const UA_DataType *types = UA_TYPES;
  783. size_t typesSize = UA_TYPES_COUNT;
  784. if(typeId->namespaceIndex != 0) {
  785. types = customTypesArray;
  786. typesSize = customTypesArraySize;
  787. }
  788. /* Iterate over the array */
  789. for(size_t i = 0; i < typesSize; ++i) {
  790. if(types[i].binaryEncodingId == typeId->identifier.numeric &&
  791. types[i].typeId.namespaceIndex == typeId->namespaceIndex)
  792. return &types[i];
  793. }
  794. return NULL;
  795. }
  796. /* ExtensionObject */
  797. static UA_StatusCode
  798. ExtensionObject_encodeBinary(UA_ExtensionObject const *src, const UA_DataType *_) {
  799. UA_Byte encoding = src->encoding;
  800. /* No content or already encoded content. Do not return
  801. * UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED after encoding the NodeId. */
  802. if(encoding <= UA_EXTENSIONOBJECT_ENCODED_XML) {
  803. UA_StatusCode retval = NodeId_encodeBinary(&src->content.encoded.typeId, NULL);
  804. if(retval != UA_STATUSCODE_GOOD)
  805. return retval;
  806. retval = encodeNumericWithExchangeBuffer(&encoding,
  807. (UA_encodeBinarySignature)Byte_encodeBinary);
  808. if(retval != UA_STATUSCODE_GOOD)
  809. return retval;
  810. switch (src->encoding) {
  811. case UA_EXTENSIONOBJECT_ENCODED_NOBODY:
  812. break;
  813. case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
  814. case UA_EXTENSIONOBJECT_ENCODED_XML:
  815. retval = ByteString_encodeBinary(&src->content.encoded.body);
  816. break;
  817. default:
  818. retval = UA_STATUSCODE_BADINTERNALERROR;
  819. }
  820. return retval;
  821. }
  822. /* Cannot encode with no data or no type description */
  823. if(!src->content.decoded.type || !src->content.decoded.data)
  824. return UA_STATUSCODE_BADENCODINGERROR;
  825. /* Write the NodeId for the binary encoded type. The NodeId is always
  826. * numeric, so no buffer replacement is taking place. */
  827. UA_NodeId typeId = src->content.decoded.type->typeId;
  828. if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  829. return UA_STATUSCODE_BADENCODINGERROR;
  830. typeId.identifier.numeric = src->content.decoded.type->binaryEncodingId;
  831. UA_StatusCode retval = NodeId_encodeBinary(&typeId, NULL);
  832. /* Write the encoding byte */
  833. encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
  834. retval |= Byte_encodeBinary(&encoding, NULL);
  835. /* Compute the content length */
  836. const UA_DataType *type = src->content.decoded.type;
  837. size_t len = UA_calcSizeBinary(src->content.decoded.data, type);
  838. /* Encode the content length */
  839. if(len > UA_INT32_MAX)
  840. return UA_STATUSCODE_BADENCODINGERROR;
  841. UA_Int32 signed_len = (UA_Int32)len;
  842. retval |= Int32_encodeBinary(&signed_len);
  843. /* Return early upon failures (no buffer exchange until here) */
  844. if(retval != UA_STATUSCODE_GOOD)
  845. return retval;
  846. /* Encode the content */
  847. return UA_encodeBinaryInternal(src->content.decoded.data, type);
  848. }
  849. static UA_StatusCode
  850. ExtensionObject_decodeBinaryContent(UA_ExtensionObject *dst, const UA_NodeId *typeId) {
  851. /* Lookup the datatype */
  852. const UA_DataType *type = findDataTypeByBinary(typeId);
  853. /* Unknown type, just take the binary content */
  854. if(!type) {
  855. dst->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
  856. dst->content.encoded.typeId = *typeId;
  857. return ByteString_decodeBinary(&dst->content.encoded.body);
  858. }
  859. /* Allocate memory */
  860. dst->content.decoded.data = UA_new(type);
  861. if(!dst->content.decoded.data)
  862. return UA_STATUSCODE_BADOUTOFMEMORY;
  863. /* Jump over the length field (TODO: check if the decoded length matches) */
  864. pos += 4;
  865. /* Decode */
  866. dst->encoding = UA_EXTENSIONOBJECT_DECODED;
  867. dst->content.decoded.type = type;
  868. size_t decode_index = type->builtin ? type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  869. return decodeBinaryJumpTable[decode_index](dst->content.decoded.data, type);
  870. }
  871. static UA_StatusCode
  872. ExtensionObject_decodeBinary(UA_ExtensionObject *dst, const UA_DataType *_) {
  873. UA_Byte encoding = 0;
  874. UA_NodeId typeId;
  875. UA_NodeId_init(&typeId);
  876. UA_StatusCode retval = NodeId_decodeBinary(&typeId, NULL);
  877. retval |= Byte_decodeBinary(&encoding, NULL);
  878. if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  879. retval = UA_STATUSCODE_BADDECODINGERROR;
  880. if(retval != UA_STATUSCODE_GOOD) {
  881. UA_NodeId_deleteMembers(&typeId);
  882. return retval;
  883. }
  884. if(encoding == UA_EXTENSIONOBJECT_ENCODED_BYTESTRING) {
  885. retval = ExtensionObject_decodeBinaryContent(dst, &typeId);
  886. } else if(encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  887. dst->encoding = (UA_ExtensionObjectEncoding)encoding;
  888. dst->content.encoded.typeId = typeId;
  889. dst->content.encoded.body = UA_BYTESTRING_NULL;
  890. } else if(encoding == UA_EXTENSIONOBJECT_ENCODED_XML) {
  891. dst->encoding = (UA_ExtensionObjectEncoding)encoding;
  892. dst->content.encoded.typeId = typeId;
  893. retval = ByteString_decodeBinary(&dst->content.encoded.body);
  894. } else {
  895. retval = UA_STATUSCODE_BADDECODINGERROR;
  896. }
  897. return retval;
  898. }
  899. /* Variant */
  900. /* Never returns UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED */
  901. static UA_StatusCode
  902. Variant_encodeBinaryWrapExtensionObject(const UA_Variant *src, const UA_Boolean isArray) {
  903. /* Default to 1 for a scalar. */
  904. size_t length = 1;
  905. /* Encode the array length if required */
  906. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  907. if(isArray) {
  908. if(src->arrayLength > UA_INT32_MAX)
  909. return UA_STATUSCODE_BADENCODINGERROR;
  910. length = src->arrayLength;
  911. UA_Int32 encodedLength = (UA_Int32)src->arrayLength;
  912. retval = Int32_encodeBinary(&encodedLength);
  913. if(retval != UA_STATUSCODE_GOOD)
  914. return retval;
  915. }
  916. /* Set up the ExtensionObject */
  917. UA_ExtensionObject eo;
  918. UA_ExtensionObject_init(&eo);
  919. eo.encoding = UA_EXTENSIONOBJECT_DECODED;
  920. eo.content.decoded.type = src->type;
  921. const UA_UInt16 memSize = src->type->memSize;
  922. uintptr_t ptr = (uintptr_t)src->data;
  923. /* Iterate over the array */
  924. for(size_t i = 0; i < length && retval == UA_STATUSCODE_GOOD; ++i) {
  925. eo.content.decoded.data = (void*)ptr;
  926. retval = UA_encodeBinaryInternal(&eo, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]);
  927. ptr += memSize;
  928. }
  929. return retval;
  930. }
  931. enum UA_VARIANT_ENCODINGMASKTYPE {
  932. UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK = 0x3F, // bits 0:5
  933. UA_VARIANT_ENCODINGMASKTYPE_DIMENSIONS = (0x01 << 6), // bit 6
  934. UA_VARIANT_ENCODINGMASKTYPE_ARRAY = (0x01 << 7) // bit 7
  935. };
  936. static UA_StatusCode
  937. Variant_encodeBinary(const UA_Variant *src, const UA_DataType *_) {
  938. /* Quit early for the empty variant */
  939. UA_Byte encoding = 0;
  940. if(!src->type)
  941. return Byte_encodeBinary(&encoding, NULL);
  942. /* Set the content type in the encoding mask */
  943. const UA_Boolean isBuiltin = src->type->builtin;
  944. if(isBuiltin)
  945. encoding |= UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK & (UA_Byte)(src->type->typeIndex + 1);
  946. else
  947. encoding |= UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK & (UA_Byte)(UA_TYPES_EXTENSIONOBJECT + 1);
  948. /* Set the array type in the encoding mask */
  949. const UA_Boolean isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL;
  950. const UA_Boolean hasDimensions = isArray && src->arrayDimensionsSize > 0;
  951. if(isArray) {
  952. encoding |= UA_VARIANT_ENCODINGMASKTYPE_ARRAY;
  953. if(hasDimensions)
  954. encoding |= UA_VARIANT_ENCODINGMASKTYPE_DIMENSIONS;
  955. }
  956. /* Encode the encoding byte */
  957. UA_StatusCode retval = Byte_encodeBinary(&encoding, NULL);
  958. if(retval != UA_STATUSCODE_GOOD)
  959. return retval;
  960. /* Encode the content */
  961. if(!isBuiltin)
  962. retval = Variant_encodeBinaryWrapExtensionObject(src, isArray);
  963. else if(!isArray)
  964. retval = UA_encodeBinaryInternal(src->data, src->type);
  965. else
  966. retval = Array_encodeBinary(src->data, src->arrayLength, src->type);
  967. /* Encode the array dimensions */
  968. if(hasDimensions && retval == UA_STATUSCODE_GOOD)
  969. retval = Array_encodeBinary(src->arrayDimensions, src->arrayDimensionsSize,
  970. &UA_TYPES[UA_TYPES_INT32]);
  971. return retval;
  972. }
  973. static UA_StatusCode
  974. Variant_decodeBinaryUnwrapExtensionObject(UA_Variant *dst) {
  975. /* Save the position in the ByteString. If unwrapping is not possible, start
  976. * from here to decode a normal ExtensionObject. */
  977. UA_Byte *old_pos = pos;
  978. /* Decode the DataType */
  979. UA_NodeId typeId;
  980. UA_NodeId_init(&typeId);
  981. UA_StatusCode retval = NodeId_decodeBinary(&typeId, NULL);
  982. if(retval != UA_STATUSCODE_GOOD)
  983. return retval;
  984. /* Decode the EncodingByte */
  985. UA_Byte encoding;
  986. retval = Byte_decodeBinary(&encoding, NULL);
  987. if(retval != UA_STATUSCODE_GOOD) {
  988. UA_NodeId_deleteMembers(&typeId);
  989. return retval;
  990. }
  991. /* Search for the datatype. Default to ExtensionObject. */
  992. if(encoding == UA_EXTENSIONOBJECT_ENCODED_BYTESTRING &&
  993. (dst->type = findDataTypeByBinary(&typeId)) != NULL) {
  994. /* Jump over the length field (TODO: check if length matches) */
  995. pos += 4;
  996. } else {
  997. /* Reset and decode as ExtensionObject */
  998. dst->type = &UA_TYPES[UA_TYPES_EXTENSIONOBJECT];
  999. pos = old_pos;
  1000. UA_NodeId_deleteMembers(&typeId);
  1001. }
  1002. /* Allocate memory */
  1003. dst->data = UA_new(dst->type);
  1004. if(!dst->data)
  1005. return UA_STATUSCODE_BADOUTOFMEMORY;
  1006. /* Decode the content */
  1007. size_t decode_index = dst->type->builtin ? dst->type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1008. retval = decodeBinaryJumpTable[decode_index](dst->data, dst->type);
  1009. if(retval != UA_STATUSCODE_GOOD) {
  1010. UA_free(dst->data);
  1011. dst->data = NULL;
  1012. }
  1013. return retval;
  1014. }
  1015. /* The resulting variant always has the storagetype UA_VARIANT_DATA. */
  1016. static UA_StatusCode
  1017. Variant_decodeBinary(UA_Variant *dst, const UA_DataType *_) {
  1018. /* Decode the encoding byte */
  1019. UA_Byte encodingByte;
  1020. UA_StatusCode retval = Byte_decodeBinary(&encodingByte, NULL);
  1021. if(retval != UA_STATUSCODE_GOOD)
  1022. return retval;
  1023. /* Return early for an empty variant (was already _inited) */
  1024. if(encodingByte == 0)
  1025. return UA_STATUSCODE_GOOD;
  1026. /* Does the variant contain an array? */
  1027. const UA_Boolean isArray = (encodingByte & UA_VARIANT_ENCODINGMASKTYPE_ARRAY) > 0;
  1028. /* Get the datatype of the content. The type must be a builtin data type.
  1029. * All not-builtin types are wrapped in an ExtensionObject. */
  1030. size_t typeIndex = (size_t)((encodingByte & UA_VARIANT_ENCODINGMASKTYPE_TYPEID_MASK) - 1);
  1031. if(typeIndex > UA_TYPES_DIAGNOSTICINFO)
  1032. return UA_STATUSCODE_BADDECODINGERROR;
  1033. dst->type = &UA_TYPES[typeIndex];
  1034. /* Decode the content */
  1035. if(isArray) {
  1036. retval = Array_decodeBinary(&dst->data, &dst->arrayLength, dst->type);
  1037. } else if(typeIndex != UA_TYPES_EXTENSIONOBJECT) {
  1038. dst->data = UA_new(dst->type);
  1039. if(!dst->data)
  1040. return UA_STATUSCODE_BADOUTOFMEMORY;
  1041. retval = decodeBinaryJumpTable[typeIndex](dst->data, dst->type);
  1042. } else {
  1043. retval = Variant_decodeBinaryUnwrapExtensionObject(dst);
  1044. }
  1045. /* Decode array dimensions */
  1046. if(isArray && (encodingByte & UA_VARIANT_ENCODINGMASKTYPE_DIMENSIONS) > 0)
  1047. retval |= Array_decodeBinary((void**)&dst->arrayDimensions,
  1048. &dst->arrayDimensionsSize, &UA_TYPES[UA_TYPES_INT32]);
  1049. return retval;
  1050. }
  1051. /* DataValue */
  1052. static UA_StatusCode
  1053. DataValue_encodeBinary(UA_DataValue const *src, const UA_DataType *_) {
  1054. /* Set up the encoding mask */
  1055. UA_Byte encodingMask = (UA_Byte)
  1056. (((UA_Byte)src->hasValue) |
  1057. ((UA_Byte)src->hasStatus << 1) |
  1058. ((UA_Byte)src->hasSourceTimestamp << 2) |
  1059. ((UA_Byte)src->hasServerTimestamp << 3) |
  1060. ((UA_Byte)src->hasSourcePicoseconds << 4) |
  1061. ((UA_Byte)src->hasServerPicoseconds << 5));
  1062. /* Encode the encoding byte */
  1063. UA_StatusCode retval = Byte_encodeBinary(&encodingMask, NULL);
  1064. if(retval != UA_STATUSCODE_GOOD)
  1065. return retval;
  1066. /* Encode the variant. Afterwards, do not return
  1067. * UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED, as the buffer might have been
  1068. * exchanged during encoding of the variant. */
  1069. if(src->hasValue) {
  1070. retval = Variant_encodeBinary(&src->value, NULL);
  1071. if(retval != UA_STATUSCODE_GOOD)
  1072. return retval;
  1073. }
  1074. if(src->hasStatus)
  1075. retval |= encodeNumericWithExchangeBuffer(&src->status,
  1076. (UA_encodeBinarySignature)UInt32_encodeBinary);
  1077. if(src->hasSourceTimestamp)
  1078. retval |= encodeNumericWithExchangeBuffer(&src->sourceTimestamp,
  1079. (UA_encodeBinarySignature)UInt64_encodeBinary);
  1080. if(src->hasSourcePicoseconds)
  1081. retval |= encodeNumericWithExchangeBuffer(&src->sourcePicoseconds,
  1082. (UA_encodeBinarySignature)UInt16_encodeBinary);
  1083. if(src->hasServerTimestamp)
  1084. retval |= encodeNumericWithExchangeBuffer(&src->serverTimestamp,
  1085. (UA_encodeBinarySignature)UInt64_encodeBinary);
  1086. if(src->hasServerPicoseconds)
  1087. retval |= encodeNumericWithExchangeBuffer(&src->serverPicoseconds,
  1088. (UA_encodeBinarySignature)UInt16_encodeBinary);
  1089. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  1090. return retval;
  1091. }
  1092. #define MAX_PICO_SECONDS 9999
  1093. static UA_StatusCode
  1094. DataValue_decodeBinary(UA_DataValue *dst, const UA_DataType *_) {
  1095. /* Decode the encoding mask */
  1096. UA_Byte encodingMask;
  1097. UA_StatusCode retval = Byte_decodeBinary(&encodingMask, NULL);
  1098. if(retval != UA_STATUSCODE_GOOD)
  1099. return retval;
  1100. /* Decode the content */
  1101. if(encodingMask & 0x01) {
  1102. dst->hasValue = true;
  1103. retval |= Variant_decodeBinary(&dst->value, NULL);
  1104. }
  1105. if(encodingMask & 0x02) {
  1106. dst->hasStatus = true;
  1107. retval |= StatusCode_decodeBinary(&dst->status);
  1108. }
  1109. if(encodingMask & 0x04) {
  1110. dst->hasSourceTimestamp = true;
  1111. retval |= DateTime_decodeBinary(&dst->sourceTimestamp);
  1112. }
  1113. if(encodingMask & 0x10) {
  1114. dst->hasSourcePicoseconds = true;
  1115. retval |= UInt16_decodeBinary(&dst->sourcePicoseconds, NULL);
  1116. if(dst->sourcePicoseconds > MAX_PICO_SECONDS)
  1117. dst->sourcePicoseconds = MAX_PICO_SECONDS;
  1118. }
  1119. if(encodingMask & 0x08) {
  1120. dst->hasServerTimestamp = true;
  1121. retval |= DateTime_decodeBinary(&dst->serverTimestamp);
  1122. }
  1123. if(encodingMask & 0x20) {
  1124. dst->hasServerPicoseconds = true;
  1125. retval |= UInt16_decodeBinary(&dst->serverPicoseconds, NULL);
  1126. if(dst->serverPicoseconds > MAX_PICO_SECONDS)
  1127. dst->serverPicoseconds = MAX_PICO_SECONDS;
  1128. }
  1129. return retval;
  1130. }
  1131. /* DiagnosticInfo */
  1132. static UA_StatusCode
  1133. DiagnosticInfo_encodeBinary(const UA_DiagnosticInfo *src, const UA_DataType *_) {
  1134. /* Set up the encoding mask */
  1135. UA_Byte encodingMask = (UA_Byte)
  1136. ((UA_Byte)src->hasSymbolicId | ((UA_Byte)src->hasNamespaceUri << 1) |
  1137. ((UA_Byte)src->hasLocalizedText << 2) | ((UA_Byte)src->hasLocale << 3) |
  1138. ((UA_Byte)src->hasAdditionalInfo << 4) | ((UA_Byte)src->hasInnerDiagnosticInfo << 5));
  1139. /* Encode the numeric content */
  1140. UA_StatusCode retval = Byte_encodeBinary(&encodingMask, NULL);
  1141. if(src->hasSymbolicId)
  1142. retval |= Int32_encodeBinary(&src->symbolicId);
  1143. if(src->hasNamespaceUri)
  1144. retval |= Int32_encodeBinary(&src->namespaceUri);
  1145. if(src->hasLocalizedText)
  1146. retval |= Int32_encodeBinary(&src->localizedText);
  1147. if(src->hasLocale)
  1148. retval |= Int32_encodeBinary(&src->locale);
  1149. if(retval != UA_STATUSCODE_GOOD)
  1150. return retval;
  1151. /* Encode the additional info */
  1152. if(src->hasAdditionalInfo) {
  1153. retval = String_encodeBinary(&src->additionalInfo, NULL);
  1154. if(retval != UA_STATUSCODE_GOOD)
  1155. return retval;
  1156. }
  1157. /* From here on, do not return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED, as
  1158. * the buffer might have been exchanged during encoding of the string. */
  1159. /* Encode the inner status code */
  1160. if(src->hasInnerStatusCode) {
  1161. retval = encodeNumericWithExchangeBuffer(&src->innerStatusCode,
  1162. (UA_encodeBinarySignature)UInt32_encodeBinary);
  1163. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  1164. if(retval != UA_STATUSCODE_GOOD)
  1165. return retval;
  1166. }
  1167. /* Encode the inner diagnostic info */
  1168. if(src->hasInnerDiagnosticInfo)
  1169. retval = UA_encodeBinaryInternal(src->innerDiagnosticInfo, &UA_TYPES[UA_TYPES_DIAGNOSTICINFO]);
  1170. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  1171. return retval;
  1172. }
  1173. static UA_StatusCode
  1174. DiagnosticInfo_decodeBinary(UA_DiagnosticInfo *dst, const UA_DataType *_) {
  1175. /* Decode the encoding mask */
  1176. UA_Byte encodingMask;
  1177. UA_StatusCode retval = Byte_decodeBinary(&encodingMask, NULL);
  1178. if(retval != UA_STATUSCODE_GOOD)
  1179. return retval;
  1180. /* Decode the content */
  1181. if(encodingMask & 0x01) {
  1182. dst->hasSymbolicId = true;
  1183. retval |= Int32_decodeBinary(&dst->symbolicId);
  1184. }
  1185. if(encodingMask & 0x02) {
  1186. dst->hasNamespaceUri = true;
  1187. retval |= Int32_decodeBinary(&dst->namespaceUri);
  1188. }
  1189. if(encodingMask & 0x04) {
  1190. dst->hasLocalizedText = true;
  1191. retval |= Int32_decodeBinary(&dst->localizedText);
  1192. }
  1193. if(encodingMask & 0x08) {
  1194. dst->hasLocale = true;
  1195. retval |= Int32_decodeBinary(&dst->locale);
  1196. }
  1197. if(encodingMask & 0x10) {
  1198. dst->hasAdditionalInfo = true;
  1199. retval |= String_decodeBinary(&dst->additionalInfo, NULL);
  1200. }
  1201. if(encodingMask & 0x20) {
  1202. dst->hasInnerStatusCode = true;
  1203. retval |= StatusCode_decodeBinary(&dst->innerStatusCode);
  1204. }
  1205. if(encodingMask & 0x40) {
  1206. /* innerDiagnosticInfo is allocated on the heap */
  1207. dst->innerDiagnosticInfo = (UA_DiagnosticInfo*)UA_calloc(1, sizeof(UA_DiagnosticInfo));
  1208. if(!dst->innerDiagnosticInfo)
  1209. return UA_STATUSCODE_BADOUTOFMEMORY;
  1210. dst->hasInnerDiagnosticInfo = true;
  1211. retval |= DiagnosticInfo_decodeBinary(dst->innerDiagnosticInfo, NULL);
  1212. }
  1213. return retval;
  1214. }
  1215. /********************/
  1216. /* Structured Types */
  1217. /********************/
  1218. static UA_StatusCode
  1219. UA_decodeBinaryInternal(void *dst, const UA_DataType *type);
  1220. const UA_encodeBinarySignature encodeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1] = {
  1221. (UA_encodeBinarySignature)Boolean_encodeBinary,
  1222. (UA_encodeBinarySignature)Byte_encodeBinary, // SByte
  1223. (UA_encodeBinarySignature)Byte_encodeBinary,
  1224. (UA_encodeBinarySignature)UInt16_encodeBinary, // Int16
  1225. (UA_encodeBinarySignature)UInt16_encodeBinary,
  1226. (UA_encodeBinarySignature)UInt32_encodeBinary, // Int32
  1227. (UA_encodeBinarySignature)UInt32_encodeBinary,
  1228. (UA_encodeBinarySignature)UInt64_encodeBinary, // Int64
  1229. (UA_encodeBinarySignature)UInt64_encodeBinary,
  1230. (UA_encodeBinarySignature)Float_encodeBinary,
  1231. (UA_encodeBinarySignature)Double_encodeBinary,
  1232. (UA_encodeBinarySignature)String_encodeBinary,
  1233. (UA_encodeBinarySignature)UInt64_encodeBinary, // DateTime
  1234. (UA_encodeBinarySignature)Guid_encodeBinary,
  1235. (UA_encodeBinarySignature)String_encodeBinary, // ByteString
  1236. (UA_encodeBinarySignature)String_encodeBinary, // XmlElement
  1237. (UA_encodeBinarySignature)NodeId_encodeBinary,
  1238. (UA_encodeBinarySignature)ExpandedNodeId_encodeBinary,
  1239. (UA_encodeBinarySignature)UInt32_encodeBinary, // StatusCode
  1240. (UA_encodeBinarySignature)UA_encodeBinaryInternal, // QualifiedName
  1241. (UA_encodeBinarySignature)LocalizedText_encodeBinary,
  1242. (UA_encodeBinarySignature)ExtensionObject_encodeBinary,
  1243. (UA_encodeBinarySignature)DataValue_encodeBinary,
  1244. (UA_encodeBinarySignature)Variant_encodeBinary,
  1245. (UA_encodeBinarySignature)DiagnosticInfo_encodeBinary,
  1246. (UA_encodeBinarySignature)UA_encodeBinaryInternal,
  1247. };
  1248. static UA_StatusCode
  1249. UA_encodeBinaryInternal(const void *src, const UA_DataType *type) {
  1250. uintptr_t ptr = (uintptr_t)src;
  1251. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1252. UA_Byte membersSize = type->membersSize;
  1253. const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] };
  1254. for(size_t i = 0; i < membersSize && retval == UA_STATUSCODE_GOOD; ++i) {
  1255. const UA_DataTypeMember *member = &type->members[i];
  1256. const UA_DataType *membertype = &typelists[!member->namespaceZero][member->memberTypeIndex];
  1257. if(!member->isArray) {
  1258. ptr += member->padding;
  1259. size_t encode_index = membertype->builtin ? membertype->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1260. size_t memSize = membertype->memSize;
  1261. UA_Byte *oldpos = pos;
  1262. retval = encodeBinaryJumpTable[encode_index]((const void*)ptr, membertype);
  1263. ptr += memSize;
  1264. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED) {
  1265. pos = oldpos; /* exchange/send the buffer */
  1266. retval = exchangeBuffer();
  1267. ptr -= member->padding + memSize; /* encode the same member in the next iteration */
  1268. --i;
  1269. }
  1270. } else {
  1271. ptr += member->padding;
  1272. const size_t length = *((const size_t*)ptr);
  1273. ptr += sizeof(size_t);
  1274. retval = Array_encodeBinary(*(void *UA_RESTRICT const *)ptr, length, membertype);
  1275. ptr += sizeof(void*);
  1276. }
  1277. }
  1278. UA_assert(retval != UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED);
  1279. return retval;
  1280. }
  1281. UA_StatusCode
  1282. UA_encodeBinary(const void *src, const UA_DataType *type,
  1283. UA_Byte **bufPos, const UA_Byte **bufEnd,
  1284. UA_exchangeEncodeBuffer exchangeCallback, void *exchangeHandle) {
  1285. /* Set the (thread-local) pointers to save function arguments */
  1286. pos = *bufPos;
  1287. end = *bufEnd;
  1288. exchangeBufferCallback = exchangeCallback;
  1289. exchangeBufferCallbackHandle = exchangeHandle;
  1290. UA_StatusCode retval = UA_encodeBinaryInternal(src, type);
  1291. /* Set the current buffer position. Beware that the buffer might have been
  1292. * exchanged internally. */
  1293. *bufPos = pos;
  1294. *bufEnd = end;
  1295. return retval;
  1296. }
  1297. const UA_decodeBinarySignature decodeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1] = {
  1298. (UA_decodeBinarySignature)Boolean_decodeBinary,
  1299. (UA_decodeBinarySignature)Byte_decodeBinary, // SByte
  1300. (UA_decodeBinarySignature)Byte_decodeBinary,
  1301. (UA_decodeBinarySignature)UInt16_decodeBinary, // Int16
  1302. (UA_decodeBinarySignature)UInt16_decodeBinary,
  1303. (UA_decodeBinarySignature)UInt32_decodeBinary, // Int32
  1304. (UA_decodeBinarySignature)UInt32_decodeBinary,
  1305. (UA_decodeBinarySignature)UInt64_decodeBinary, // Int64
  1306. (UA_decodeBinarySignature)UInt64_decodeBinary,
  1307. (UA_decodeBinarySignature)Float_decodeBinary,
  1308. (UA_decodeBinarySignature)Double_decodeBinary,
  1309. (UA_decodeBinarySignature)String_decodeBinary,
  1310. (UA_decodeBinarySignature)UInt64_decodeBinary, // DateTime
  1311. (UA_decodeBinarySignature)Guid_decodeBinary,
  1312. (UA_decodeBinarySignature)String_decodeBinary, // ByteString
  1313. (UA_decodeBinarySignature)String_decodeBinary, // XmlElement
  1314. (UA_decodeBinarySignature)NodeId_decodeBinary,
  1315. (UA_decodeBinarySignature)ExpandedNodeId_decodeBinary,
  1316. (UA_decodeBinarySignature)UInt32_decodeBinary, // StatusCode
  1317. (UA_decodeBinarySignature)UA_decodeBinaryInternal, // QualifiedName
  1318. (UA_decodeBinarySignature)LocalizedText_decodeBinary,
  1319. (UA_decodeBinarySignature)ExtensionObject_decodeBinary,
  1320. (UA_decodeBinarySignature)DataValue_decodeBinary,
  1321. (UA_decodeBinarySignature)Variant_decodeBinary,
  1322. (UA_decodeBinarySignature)DiagnosticInfo_decodeBinary,
  1323. (UA_decodeBinarySignature)UA_decodeBinaryInternal
  1324. };
  1325. static UA_StatusCode
  1326. UA_decodeBinaryInternal(void *dst, const UA_DataType *type) {
  1327. uintptr_t ptr = (uintptr_t)dst;
  1328. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1329. UA_Byte membersSize = type->membersSize;
  1330. const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] };
  1331. for(size_t i = 0; i < membersSize; ++i) {
  1332. const UA_DataTypeMember *member = &type->members[i];
  1333. const UA_DataType *membertype = &typelists[!member->namespaceZero][member->memberTypeIndex];
  1334. if(!member->isArray) {
  1335. ptr += member->padding;
  1336. size_t fi = membertype->builtin ? membertype->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1337. size_t memSize = membertype->memSize;
  1338. retval |= decodeBinaryJumpTable[fi]((void *UA_RESTRICT)ptr, membertype);
  1339. ptr += memSize;
  1340. } else {
  1341. ptr += member->padding;
  1342. size_t *length = (size_t*)ptr;
  1343. ptr += sizeof(size_t);
  1344. retval |= Array_decodeBinary((void *UA_RESTRICT *UA_RESTRICT)ptr, length, membertype);
  1345. ptr += sizeof(void*);
  1346. }
  1347. }
  1348. return retval;
  1349. }
  1350. UA_StatusCode
  1351. UA_decodeBinary(const UA_ByteString *src, size_t *offset, void *dst,
  1352. const UA_DataType *type, size_t customTypesSize,
  1353. const UA_DataType *customTypes) {
  1354. /* Initialize the destination */
  1355. memset(dst, 0, type->memSize);
  1356. /* Store the pointers to the custom datatypes. They might be needed during
  1357. * decoding of variants. */
  1358. customTypesArraySize = customTypesSize;
  1359. customTypesArray = customTypes;
  1360. /* Set the (thread-local) position and end pointers to save function
  1361. * arguments */
  1362. pos = &src->data[*offset];
  1363. end = &src->data[src->length];
  1364. /* Decode */
  1365. UA_StatusCode retval = UA_decodeBinaryInternal(dst, type);
  1366. /* Clean up */
  1367. if(retval == UA_STATUSCODE_GOOD)
  1368. *offset = (size_t)(pos - src->data) / sizeof(UA_Byte);
  1369. else
  1370. UA_deleteMembers(dst, type);
  1371. return retval;
  1372. }
  1373. /******************/
  1374. /* CalcSizeBinary */
  1375. /******************/
  1376. static size_t
  1377. Array_calcSizeBinary(const void *src, size_t length, const UA_DataType *type) {
  1378. size_t s = 4; // length
  1379. if(type->overlayable) {
  1380. s += type->memSize * length;
  1381. return s;
  1382. }
  1383. uintptr_t ptr = (uintptr_t)src;
  1384. size_t encode_index = type->builtin ? type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1385. for(size_t i = 0; i < length; ++i) {
  1386. s += calcSizeBinaryJumpTable[encode_index]((const void*)ptr, type);
  1387. ptr += type->memSize;
  1388. }
  1389. return s;
  1390. }
  1391. static size_t
  1392. calcSizeBinaryMemSize(const void *UA_RESTRICT p, const UA_DataType *type) {
  1393. return type->memSize;
  1394. }
  1395. static size_t
  1396. String_calcSizeBinary(const UA_String *UA_RESTRICT p, const UA_DataType *_) {
  1397. return 4 + p->length;
  1398. }
  1399. static size_t
  1400. Guid_calcSizeBinary(const UA_Guid *UA_RESTRICT p, const UA_DataType *_) {
  1401. return 16;
  1402. }
  1403. static size_t
  1404. NodeId_calcSizeBinary(const UA_NodeId *UA_RESTRICT src, const UA_DataType *_) {
  1405. size_t s = 1; // encoding byte
  1406. switch (src->identifierType) {
  1407. case UA_NODEIDTYPE_NUMERIC:
  1408. if(src->identifier.numeric > UA_UINT16_MAX || src->namespaceIndex > UA_BYTE_MAX) {
  1409. s += 6;
  1410. } else if(src->identifier.numeric > UA_BYTE_MAX || src->namespaceIndex > 0) {
  1411. s += 3;
  1412. } else {
  1413. s += 1;
  1414. }
  1415. break;
  1416. case UA_NODEIDTYPE_BYTESTRING:
  1417. case UA_NODEIDTYPE_STRING:
  1418. s += 2;
  1419. s += String_calcSizeBinary(&src->identifier.string, NULL);
  1420. break;
  1421. case UA_NODEIDTYPE_GUID:
  1422. s += 18;
  1423. break;
  1424. default:
  1425. return 0;
  1426. }
  1427. return s;
  1428. }
  1429. static size_t
  1430. ExpandedNodeId_calcSizeBinary(const UA_ExpandedNodeId *src, const UA_DataType *_) {
  1431. size_t s = NodeId_calcSizeBinary(&src->nodeId, NULL);
  1432. if(src->namespaceUri.length > 0)
  1433. s += String_calcSizeBinary(&src->namespaceUri, NULL);
  1434. if(src->serverIndex > 0)
  1435. s += 4;
  1436. return s;
  1437. }
  1438. static size_t
  1439. LocalizedText_calcSizeBinary(const UA_LocalizedText *src, UA_DataType *_) {
  1440. size_t s = 1; // encoding byte
  1441. if(src->locale.data)
  1442. s += String_calcSizeBinary(&src->locale, NULL);
  1443. if(src->text.data)
  1444. s += String_calcSizeBinary(&src->text, NULL);
  1445. return s;
  1446. }
  1447. static size_t
  1448. ExtensionObject_calcSizeBinary(const UA_ExtensionObject *src, UA_DataType *_) {
  1449. size_t s = 1; // encoding byte
  1450. if(src->encoding > UA_EXTENSIONOBJECT_ENCODED_XML) {
  1451. if(!src->content.decoded.type || !src->content.decoded.data)
  1452. return 0;
  1453. if(src->content.decoded.type->typeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  1454. return 0;
  1455. s += NodeId_calcSizeBinary(&src->content.decoded.type->typeId, NULL);
  1456. s += 4; // length
  1457. const UA_DataType *type = src->content.decoded.type;
  1458. size_t encode_index = type->builtin ? type->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1459. s += calcSizeBinaryJumpTable[encode_index](src->content.decoded.data, type);
  1460. } else {
  1461. s += NodeId_calcSizeBinary(&src->content.encoded.typeId, NULL);
  1462. switch (src->encoding) {
  1463. case UA_EXTENSIONOBJECT_ENCODED_NOBODY:
  1464. break;
  1465. case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
  1466. case UA_EXTENSIONOBJECT_ENCODED_XML:
  1467. s += String_calcSizeBinary(&src->content.encoded.body, NULL);
  1468. break;
  1469. default:
  1470. return 0;
  1471. }
  1472. }
  1473. return s;
  1474. }
  1475. static size_t
  1476. Variant_calcSizeBinary(UA_Variant const *src, UA_DataType *_) {
  1477. size_t s = 1; /* encoding byte */
  1478. if(!src->type)
  1479. return s;
  1480. UA_Boolean isArray = src->arrayLength > 0 || src->data <= UA_EMPTY_ARRAY_SENTINEL;
  1481. UA_Boolean hasDimensions = isArray && src->arrayDimensionsSize > 0;
  1482. UA_Boolean isBuiltin = src->type->builtin;
  1483. UA_NodeId typeId;
  1484. UA_NodeId_init(&typeId);
  1485. size_t encode_index = src->type->typeIndex;
  1486. if(!isBuiltin) {
  1487. encode_index = UA_BUILTIN_TYPES_COUNT;
  1488. typeId = src->type->typeId;
  1489. if(typeId.identifierType != UA_NODEIDTYPE_NUMERIC)
  1490. return 0;
  1491. }
  1492. size_t length = src->arrayLength;
  1493. if(isArray)
  1494. s += 4;
  1495. else
  1496. length = 1;
  1497. uintptr_t ptr = (uintptr_t)src->data;
  1498. size_t memSize = src->type->memSize;
  1499. for(size_t i = 0; i < length; ++i) {
  1500. if(!isBuiltin) {
  1501. /* The type is wrapped inside an extensionobject */
  1502. s += NodeId_calcSizeBinary(&typeId, NULL);
  1503. s += 1 + 4; // encoding byte + length
  1504. }
  1505. s += calcSizeBinaryJumpTable[encode_index]((const void*)ptr, src->type);
  1506. ptr += memSize;
  1507. }
  1508. if(hasDimensions)
  1509. s += Array_calcSizeBinary(src->arrayDimensions, src->arrayDimensionsSize,
  1510. &UA_TYPES[UA_TYPES_INT32]);
  1511. return s;
  1512. }
  1513. static size_t
  1514. DataValue_calcSizeBinary(const UA_DataValue *src, UA_DataType *_) {
  1515. size_t s = 1; // encoding byte
  1516. if(src->hasValue)
  1517. s += Variant_calcSizeBinary(&src->value, NULL);
  1518. if(src->hasStatus)
  1519. s += 4;
  1520. if(src->hasSourceTimestamp)
  1521. s += 8;
  1522. if(src->hasSourcePicoseconds)
  1523. s += 2;
  1524. if(src->hasServerTimestamp)
  1525. s += 8;
  1526. if(src->hasServerPicoseconds)
  1527. s += 2;
  1528. return s;
  1529. }
  1530. static size_t
  1531. DiagnosticInfo_calcSizeBinary(const UA_DiagnosticInfo *src, UA_DataType *_) {
  1532. size_t s = 1; // encoding byte
  1533. if(src->hasSymbolicId)
  1534. s += 4;
  1535. if(src->hasNamespaceUri)
  1536. s += 4;
  1537. if(src->hasLocalizedText)
  1538. s += 4;
  1539. if(src->hasLocale)
  1540. s += 4;
  1541. if(src->hasAdditionalInfo)
  1542. s += String_calcSizeBinary(&src->additionalInfo, NULL);
  1543. if(src->hasInnerStatusCode)
  1544. s += 4;
  1545. if(src->hasInnerDiagnosticInfo)
  1546. s += DiagnosticInfo_calcSizeBinary(src->innerDiagnosticInfo, NULL);
  1547. return s;
  1548. }
  1549. const UA_calcSizeBinarySignature calcSizeBinaryJumpTable[UA_BUILTIN_TYPES_COUNT + 1] = {
  1550. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Boolean
  1551. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Byte
  1552. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize,
  1553. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Int16
  1554. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize,
  1555. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Int32
  1556. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize,
  1557. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Int64
  1558. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize,
  1559. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Float
  1560. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // Double
  1561. (UA_calcSizeBinarySignature)String_calcSizeBinary,
  1562. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // DateTime
  1563. (UA_calcSizeBinarySignature)Guid_calcSizeBinary,
  1564. (UA_calcSizeBinarySignature)String_calcSizeBinary, // ByteString
  1565. (UA_calcSizeBinarySignature)String_calcSizeBinary, // XmlElement
  1566. (UA_calcSizeBinarySignature)NodeId_calcSizeBinary,
  1567. (UA_calcSizeBinarySignature)ExpandedNodeId_calcSizeBinary,
  1568. (UA_calcSizeBinarySignature)calcSizeBinaryMemSize, // StatusCode
  1569. (UA_calcSizeBinarySignature)UA_calcSizeBinary, // QualifiedName
  1570. (UA_calcSizeBinarySignature)LocalizedText_calcSizeBinary,
  1571. (UA_calcSizeBinarySignature)ExtensionObject_calcSizeBinary,
  1572. (UA_calcSizeBinarySignature)DataValue_calcSizeBinary,
  1573. (UA_calcSizeBinarySignature)Variant_calcSizeBinary,
  1574. (UA_calcSizeBinarySignature)DiagnosticInfo_calcSizeBinary,
  1575. (UA_calcSizeBinarySignature)UA_calcSizeBinary
  1576. };
  1577. size_t
  1578. UA_calcSizeBinary(void *p, const UA_DataType *type) {
  1579. size_t s = 0;
  1580. uintptr_t ptr = (uintptr_t)p;
  1581. UA_Byte membersSize = type->membersSize;
  1582. const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] };
  1583. for(size_t i = 0; i < membersSize; ++i) {
  1584. const UA_DataTypeMember *member = &type->members[i];
  1585. const UA_DataType *membertype = &typelists[!member->namespaceZero][member->memberTypeIndex];
  1586. if(!member->isArray) {
  1587. ptr += member->padding;
  1588. size_t encode_index = membertype->builtin ? membertype->typeIndex : UA_BUILTIN_TYPES_COUNT;
  1589. s += calcSizeBinaryJumpTable[encode_index]((const void*)ptr, membertype);
  1590. ptr += membertype->memSize;
  1591. } else {
  1592. ptr += member->padding;
  1593. const size_t length = *((const size_t*)ptr);
  1594. ptr += sizeof(size_t);
  1595. s += Array_calcSizeBinary(*(void *UA_RESTRICT const *)ptr, length, membertype);
  1596. ptr += sizeof(void*);
  1597. }
  1598. }
  1599. return s;
  1600. }