Debian Codegraph @

core/libs/dngwriter/extra/xmp_sdk/source/XMP_LibUtils.hpp

raw
1 #ifndef __XMP_LibUtils_hpp__
2 #define __XMP_LibUtils_hpp__ 1
3
4 // =================================================================================================
5 // Copyright 2009 Adobe
6 // All Rights Reserved.
7 //
8 // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
9 // of the Adobe license agreement accompanying it. If you have received this file from a source other
10 // than Adobe, then your use, modification, or distribution of it requires the prior written permission
11 // of Adobe.
12 // =================================================================================================
13
14 #if AdobePrivate
15 // =================================================================================================
16 // Change history
17 // ==============
18 //
19 // Writers:
20 // AWL Alan Lillich
21 // JEH Joerg Ehrlich
22 // SAM Samy Makki
23 // ADC Amandeep Chawla
24 // HK Honey Kansal
25 // AB Amit Bhatti
26 //
27 // mm-dd-yy who M.m-bbb Description of changes, most recent on top.
28 //
29 // 01-05-15 AB 5.6-f122 Provide more functionalities to Plugin( Existing XMP packet, PacketInfo, OpenFlags, Error Callback and progress notification),
30 // more standard handler access API getFileModDate,IsMetadataWritable,putXMP,getAssociatedResources.
31 // New plugin handler for MPEG4 with Exif support.
32 // 02-21-14 ADC 5.6-c001 XMPCommon Framework and XMPCore new APIs ported to Mac Environment.
33 //
34 // 01-03-14 HK 5.6-f087 [3688857] Fixing data alignment issues on ARM processor.
35 // 02-13-13 ADC 5.6-f035 [3498686, 3497304] XMP GetFileModDate() is extremely slow.
36 //
37 // 10-10-12 ADC 5.5-c012 Changed internal implementation of common error notification infrastructure.
38 // 08-08-12 AWL 5.5-c007 XMPCore error notifications for one case of XML parsing, no existing test failures.
39 //
40 // 02-02-11 SAM 5.3-f026 Adding XMP_Throw_Verbose macro for Debug only in order to
41 // add internal error codes to the message.
42 // 02-05-10 AWL 5.1-c002 Fix build warnings from Xcode 3.2.
43 //
44 // 07-03-09 JEH 5.0-c043 Fix Vista RWLock section
45 // 06-23-09 AWL 5.0-c040-f049 Add hack to revert to global DLL locking.
46 // 06-23-09 AWL 5.0-c039-f048 Fix atomic increment and decrement to be optional, not on Solaris.
47 // 06-22-09 AWL 5.0-c038-f047 Fix locking code to use atomic increment and decrement.
48 // 06-18-09 AWL 5.0-c037-f046 Minor tweaks from code review.
49 // 06-15-09 AWL 5.0-c036 Mark critical locking variables volatile, fix all namespace table usage to be clean.
50 // 06-12-09 AWL 5.0-c035-f045 Simplify the multiple lock permutations.
51 // 06-11-09 AWL 5.0-c034-f043 Finish threading revamp, implement friendly reader/writer locking.
52 //
53 // =================================================================================================
54 #endif // AdobePrivate
55
56 #include "public/include/XMP_Environment.h" // ! Must be the first include.
57 #include "public/include/XMP_Const.h"
58
59 #include <map>
60 #include <string>
61 #include <vector>
62
63 #if XMP_DebugBuild
64 #include <cassert>
65 #endif
66
67 #if XMP_WinBuild
68 #ifndef snprintf
69 #define snprintf _snprintf
70 #endif
71 #endif
72
73 // =================================================================================================
74 // Basic types, constants
75 // ======================
76
77 #define kTab ((char)0x09)
78 #define kLF ((char)0x0A)
79 #define kCR ((char)0x0D)
80
81 #if XMP_WinBuild
82 #define kDirChar '\\'
83 #else
84 #define kDirChar '/'
85 #endif
86
87 typedef std::string XMP_VarString;
88
89 #define EliminateGlobal(g) delete ( g ); g = 0
90
91 extern "C" bool Initialize_LibUtils();
92 extern "C" void Terminate_LibUtils();
93
94 #define IgnoreParam(p) (void)p
95
96 // The builtin offsetof macro sometimes violates C++ data member rules.
97 #define XMP_OffsetOf(struct,field) ( (char*)(&((struct*)0x100)->field) - (char*)0x100 )
98
99 // =================================================================================================
100 // Support for exceptions and asserts
101 // ==================================
102
103 #define AnnounceThrow(msg) /* Do nothing. */
104 #define AnnounceCatch(msg) /* Do nothing. */
105
106 #define XMP_Throw(msg,id) { AnnounceThrow ( msg ); throw XMP_Error ( id, msg ); }
107
108 #if XMP_DebugBuild
109 #define XMP_Throw_Verbose(msg,e,id) \
110 { \
111 char tmpMsg[255]; \
112 snprintf(tmpMsg, sizeof(tmpMsg), #msg "( %d )", e); \
113 XMP_Throw( tmpMsg, id); \
114 }
115 #else
116 #define XMP_Throw_Verbose(msg,e,id) XMP_Throw(msg, id)
117 #endif
118
119 #define XMP_Error_Throw(error) { AnnounceThrow (error.GetErrMsg()); throw error; }
120
121 class GenericErrorCallback {
122 public:
123 // Abstract base class for XMPCore and XMPFiles internal error notification support. Needed so
124 // that the XMLParserAdapter (used by both XMPCore and XMPFiles) can send error notifications,
125 // and so that utility parts of just XMPCore or XMPFiles can avoid dependence on XMPCore.hpp or
126 // XMPFiles.hpp if that is appropriate.
127
128 XMP_Uns32 limit;
129 mutable XMP_Uns32 notifications;
130 mutable XMP_ErrorSeverity topSeverity;
131
132 GenericErrorCallback() : notifications(0), limit(1), topSeverity(kXMPErrSev_Recoverable) {};
133 virtual ~GenericErrorCallback() {};
134
135 void Clear() { this->notifications = 0; this->limit = 1; this->topSeverity = kXMPErrSev_Recoverable; };
136
137 bool CheckLimitAndSeverity (XMP_ErrorSeverity severity ) const
138 {
139
140 if ( this->limit == 0 ) return true; // Always notify if the limit is zero.
141 if ( severity < this->topSeverity ) return false; // Don't notify, don't count.
142
143 if ( severity > this->topSeverity ) {
144 this->topSeverity = severity;
145 this->notifications = 0;
146 }
147
148 this->notifications += 1;
149 return (this->notifications <= this->limit);
150
151 } // GenericErrorCallback::CheckLimitAndSeverity
152
153 // Const so they can be used with const XMPMeta and XMPFiles objects.
154 void NotifyClient ( XMP_ErrorSeverity severity, XMP_Error & error, XMP_StringPtr filePath = 0 ) const
155 {
156
157 bool notifyClient = CanNotify() && !error.IsNotified();
158 bool returnAndRecover (severity == kXMPErrSev_Recoverable);
159
160 if ( notifyClient ) {
161 error.SetNotified();
162 notifyClient = CheckLimitAndSeverity ( severity );
163 if ( notifyClient ) {
164 returnAndRecover &= ClientCallbackWrapper( filePath, severity, error.GetID(), error.GetErrMsg() );
165 }
166 }
167
168 if ( ! returnAndRecover ) XMP_Error_Throw ( error );
169
170 } // GenericErrorCallback::NotifyClient
171
172 virtual bool CanNotify ( ) const = 0;
173 virtual bool ClientCallbackWrapper ( XMP_StringPtr filePath, XMP_ErrorSeverity severity, XMP_Int32 cause, XMP_StringPtr messsage ) const = 0;
174
175 };
176
177 // -------------------------------------------------------------------------------------------------
178
179 struct ErrorCallbackBox
180 {
181 XMPFiles_ErrorCallbackWrapper wrapperProc;
182 XMPFiles_ErrorCallbackProc clientProc;
183 void * context;
184 XMP_Uns32 limit;
185
186 ErrorCallbackBox( XMPFiles_ErrorCallbackWrapper wrapperProcedure,
187 XMPFiles_ErrorCallbackProc clientProcedure,
188 void * contextPtr,
189 XMP_Uns32 limit32 ): wrapperProc(wrapperProcedure), clientProc(clientProcedure), context(contextPtr), limit(limit32) { }
190 };
191
192 // -------------------------------------------------------------------------------------------------
193
194 #define _MakeStr(p) #p
195 #define _NotifyMsg(n,c,f,l) #n " failed: " #c " in " f " at line " _MakeStr(l)
196 #define _ExplicitMsg(msg,c,e) #e " " #msg ": " #c
197
198 #if AdobePrivate
199 extern "C" void XMP_PUBLIC XMP_GetAssertNotify ( XMP_AssertNotifyProc* notifyProc, void** refCon );
200 #endif
201
202 #define XMP_Validate(c,msg,e) \
203 if ( ! (c) ) { \
204 const char * validate_msg = _ExplicitMsg ( msg, c, e ); \
205 XMP_Throw ( validate_msg, e ); \
206 }
207
208 // This statement is needed in XMP_Assert definition to reduce warnings from
209 // static analysis tool in Visual Studio. Defined here, as platform fork not
210 // possible within macro definition below
211 #if XMP_WinBuild
212 #define analysis_assume(c) __analysis_assume( c );
213 #else
214 #define analysis_assume(c) ((void) 0)
215 #endif
216
217 #if ! XMP_DebugBuild
218 #define XMP_Assert(c) ((void) 0)
219 #else
220 #if ! AdobePrivate
221 #define XMP_Assert(c) assert ( c )
222 #else
223 #define XMP_Assert(c) \
224 if ( ! (c) ) { \
225 XMP_AssertNotifyProc notifyProc; \
226 void * _refCon; \
227 XMP_GetAssertNotify ( &notifyProc, &_refCon ); \
228 if ( notifyProc == 0 ) { \
229 assert ( c ); \
230 analysis_assume(c); /* To reduce security warnings from static analysis in VS */\
231 } else { \
232 const char * assert_msg = _NotifyMsg ( XMP_Assert, (c), __FILE__, __LINE__ ); \
233 (*notifyProc) ( _refCon, assert_msg ); \
234 XMP_Throw ( assert_msg , kXMPErr_AssertFailure ); \
235 } \
236 }
237 #endif
238 #endif
239
240 #if ! AdobePrivate
241 #define XMP_Enforce(c) \
242 if ( ! (c) ) { \
243 const char * assert_msg = _NotifyMsg ( XMP_Enforce, (c), __FILE__, __LINE__ ); \
244 XMP_Throw ( assert_msg , kXMPErr_EnforceFailure ); \
245 }
246 #else
247 #define XMP_Enforce(c) \
248 if ( ! (c) ) { \
249 XMP_AssertNotifyProc notifyProc; \
250 void * refCon; \
251 XMP_GetAssertNotify ( &notifyProc, &refCon ); \
252 const char * assert_msg = _NotifyMsg ( XMP_Enforce, (c), __FILE__, __LINE__ ); \
253 if ( notifyProc != 0 ) (*notifyProc) ( refCon, assert_msg ); \
254 XMP_Throw ( assert_msg, kXMPErr_EnforceFailure ); \
255 }
256 #endif
257
258 #if ! AdobePrivate
259 #define XMP_Enforce_NoThrow(c)
260 #else
261 #define XMP_Enforce_NoThrow(c) \
262 if ( ! (c) ) { \
263 XMP_AssertNotifyProc notifyProc; \
264 void * refCon; \
265 XMP_GetAssertNotify ( &notifyProc, &refCon ); \
266 const char * assert_msg = _NotifyMsg ( XMP_Enforce, (c), __FILE__, __LINE__ ); \
267 if ( notifyProc != 0 ) (*notifyProc) ( refCon, assert_msg ); \
268 }
269 #endif
270
271 // =================================================================================================
272 // Thread synchronization locks
273 // ============================
274
275 // About XMP and thread synchronization
276 //
277 // A variety of choices are provided for thread synchronization. Exactly one method must be chosen
278 // by defining the appropriate symbol to 1.
279 //
280 // * UseNoLock - This choice turns the synchronization functions into no-ops. It must only be used
281 // by single threaded clients, or clients providing their own control at a higher level.
282 //
283 // * UseGlobalLibraryLock - This choice uses a single per-library lock. The result is thread safe
284 // but unfriendly behavior, no true concurrency. This should only be used as a debugging fallback.
285 //
286 // * UseBoostLock - This choice uses the Boost shared_mutex mechanism. It has the advantage of being
287 // robust and being available on pretty much all platforms. It has the disadvantage of requiring
288 // the developer to download, integrate, and build the Boost thread library.
289 //
290 // * UsePThreadLock - This choice uses the POSIX pthread rwlock mechanism. It has the advantage of
291 // being robust and being available on any modern UNIX platform, including Mac OS X.
292 //
293 // * UseWinSlimLock - This choice uses the Windows slim reader/writer mechanism. It is robust but
294 // only available on Vista and newer versions of Windows, it is not available on XP.
295 //
296 // * UseHomeGrownLock - This choice uses local code plus lower level synchronization primitives. It
297 // has the advantage of being usable on all platforms, and having exposed and tunable policy. It
298 // has the disadvantage of possibly being less robust than Boost or the O/S provided mechanisms.
299 // The lower level synchronization primitives are pthread mutex and condition for UNIX (including
300 // Mac OS X). For Windows there is a choice of critical section and condition variable for Vista
301 // and newer; or critical section, event, and semaphore for XP and newer.
302
303 #define UseHomeGrownLock 1
304
305 // -------------------------------------------------------------------------------------------------
306 // A basic exclusive access mutex and atomic increment/decrement operations.
307
308 #if XMP_WinBuild
309
310 #include <Windows.h>
311
312 #define HaveAtomicIncrDecr 1
313 typedef LONG XMP_AtomicCounter;
314
315 #define XMP_AtomicIncrement(x) InterlockedIncrement ( &(x) )
316 #define XMP_AtomicDecrement(x) InterlockedDecrement ( &(x) )
317
318 typedef CRITICAL_SECTION XMP_BasicMutex;
319
320 #define InitializeBasicMutex(mutex) { InitializeCriticalSection ( &mutex ); }
321 #define TerminateBasicMutex(mutex) { DeleteCriticalSection ( &mutex ); }
322 #define AcquireBasicMutex(mutex) { EnterCriticalSection ( &mutex ); }
323 #define ReleaseBasicMutex(mutex) { LeaveCriticalSection ( &mutex ); }
324
325 #elif XMP_MacBuild | XMP_iOSBuild
326
327 #include <pthread.h>
328
329 // #include <libkern/OSAtomic.h> deprecated header
330 #include <atomic>
331
332 #define HaveAtomicIncrDecr 1
333 //typedef int32_t XMP_AtomicCounter; //Changing XMP_AtomicCounter type to std::atomic
334 // due to deprecation of mac os APIs
335
336
337 typedef std::atomic<int32_t> XMP_AtomicCounter;
338
339 //Both these APIs are deprecated.
340
341 //#define XMP_AtomicIncrement(x) OSAtomicIncrement32Barrier ( &(x) )
342 //#define XMP_AtomicDecrement(x) OSAtomicDecrement32Barrier ( &(x) )
343
344 #define XMP_AtomicIncrement(x) std::atomic_fetch_add ( &(x), 1 )
345 #define XMP_AtomicDecrement(x) std::atomic_fetch_sub ( &(x), 1 )
346
347 typedef pthread_mutex_t XMP_BasicMutex;
348
349 #define InitializeBasicMutex(mutex) { int err = pthread_mutex_init ( &mutex, 0 ); XMP_Enforce ( err == 0 ); }
350 #define TerminateBasicMutex(mutex) { int err = pthread_mutex_destroy ( &mutex ); XMP_Enforce_NoThrow ( err == 0 ); }
351 #define AcquireBasicMutex(mutex) { int err = pthread_mutex_lock ( &mutex ); XMP_Enforce ( err == 0 ); }
352 #define ReleaseBasicMutex(mutex) { int err = pthread_mutex_unlock ( &mutex ); XMP_Enforce ( err == 0 ); }
353
354 #elif XMP_UNIXBuild || XMP_AndroidBuild
355
356 #include <pthread.h>
357
358 // Atomic increment/decrement intrinsics should be in gcc 4.1, but Solaris seems to lack them.
359 #ifndef HaveAtomicIncrDecr
360 #define HaveAtomicIncrDecr 1
361 #endif
362 #if HaveAtomicIncrDecr
363 typedef XMP_Uns32 XMP_AtomicCounter;
364 #define XMP_AtomicIncrement(x) __sync_add_and_fetch ( &(x), 1 )
365 #define XMP_AtomicDecrement(x) __sync_sub_and_fetch ( &(x), 1 )
366 #endif
367
368 typedef pthread_mutex_t XMP_BasicMutex;
369
370 #define InitializeBasicMutex(mutex) { int err = pthread_mutex_init ( &mutex, 0 ); XMP_Enforce ( err == 0 ); }
371 #define TerminateBasicMutex(mutex) { int err = pthread_mutex_destroy ( &mutex ); XMP_Enforce_NoThrow ( err == 0 ); }
372 #define AcquireBasicMutex(mutex) { int err = pthread_mutex_lock ( &mutex ); XMP_Enforce ( err == 0 ); }
373 #define ReleaseBasicMutex(mutex) { int err = pthread_mutex_unlock ( &mutex ); XMP_Enforce ( err == 0 ); }
374
375 #endif
376
377 class XMP_AutoMutex {
378 public:
379 XMP_AutoMutex ( XMP_BasicMutex * _mutex ) : mutex(_mutex) { AcquireBasicMutex ( *this->mutex ); }
380 ~XMP_AutoMutex() { this->Release(); }
381 void Release() { if ( this->mutex != 0 ) ReleaseBasicMutex ( *this->mutex ); this->mutex = 0; }
382 private:
383 XMP_BasicMutex * mutex;
384 XMP_AutoMutex() {}; // ! Must not be used.
385 };
386
387 // -------------------------------------------------------------------------------------------------
388 // Details for the various locking mechanisms.
389
390 #if UseNoLock
391
392 typedef void* XMP_BasicRWLock; // For single threaded clients that want maximum performance.
393
394 #define XMP_BasicRWLock_Initialize(lck) /* Do nothing. */
395 #define XMP_BasicRWLock_Terminate(lck) /* Do nothing. */
396
397 #define XMP_BasicRWLock_AcquireForRead(lck) /* Do nothing. */
398 #define XMP_BasicRWLock_AcquireForWrite(lck) /* Do nothing. */
399
400 #define XMP_BasicRWLock_ReleaseFromRead(lck) /* Do nothing. */
401 #define XMP_BasicRWLock_ReleaseFromWrite(lck) /* Do nothing. */
402
403 #elif UseGlobalLibraryLock
404
405 extern XMP_BasicMutex sLibraryLock;
406
407 typedef void* XMP_BasicRWLock; // Use the old thread-unfriendly per-DLL mutex.
408
409 #define XMP_BasicRWLock_Initialize(lck) /* Do nothing. */
410 #define XMP_BasicRWLock_Terminate(lck) /* Do nothing. */
411
412 #define XMP_BasicRWLock_AcquireForRead(lck) /* Do nothing. */
413 #define XMP_BasicRWLock_AcquireForWrite(lck) /* Do nothing. */
414
415 #define XMP_BasicRWLock_ReleaseFromRead(lck) /* Do nothing. */
416 #define XMP_BasicRWLock_ReleaseFromWrite(lck) /* Do nothing. */
417
418 #elif UseBoostLock
419
420 #include <boost/thread/shared_mutex.hpp>
421 typedef boost::shared_mutex XMP_BasicRWLock;
422
423 #define XMP_BasicRWLock_Initialize(lck) /* Do nothing. */
424 #define XMP_BasicRWLock_Terminate(lck) /* Do nothing. */
425
426 #define XMP_BasicRWLock_AcquireForRead(lck) lck.lock_shared()
427 #define XMP_BasicRWLock_AcquireForWrite(lck) lck.lock()
428
429 #define XMP_BasicRWLock_ReleaseFromRead(lck) lck.unlock_shared()
430 #define XMP_BasicRWLock_ReleaseFromWrite(lck) lck.unlock()
431
432 #elif UsePThreadLock
433
434 #include <pthread.h>
435 typedef pthread_rwlock_t XMP_BasicRWLock;
436
437 #define XMP_BasicRWLock_Initialize(lck) \
438 { int err = pthread_rwlock_init ( &lck, 0 ); \
439 if ( err != 0 ) XMP_Throw ( "Initialize pthread rwlock failed", kXMPErr_ExternalFailure ); }
440 #define XMP_BasicRWLock_Terminate(lck) \
441 { int err = pthread_rwlock_destroy ( &lck ); XMP_Assert ( err == 0 ); }
442
443 #define XMP_BasicRWLock_AcquireForRead(lck) \
444 { int err = pthread_rwlock_rdlock ( &lck ); \
445 if ( err != 0 ) XMP_Throw ( "Acquire pthread read lock failed", kXMPErr_ExternalFailure ); }
446 #define XMP_BasicRWLock_AcquireForWrite(lck) \
447 { int err = pthread_rwlock_wrlock ( &lck ); \
448 if ( err != 0 ) XMP_Throw ( "Acquire pthread write lock failed", kXMPErr_ExternalFailure ); }
449
450 #define XMP_BasicRWLock_ReleaseFromRead(lck) \
451 { int err = pthread_rwlock_unlock ( &lck ); \
452 if ( err != 0 ) XMP_Throw ( "Release pthread read lock failed", kXMPErr_ExternalFailure ); }
453 #define XMP_BasicRWLock_ReleaseFromWrite(lck) \
454 { int err = pthread_rwlock_unlock ( &lck ); \
455 if ( err != 0 ) XMP_Throw ( "Release pthread write lock failed", kXMPErr_ExternalFailure ); }
456
457 #elif UseWinSlimLock
458
459 #include <Windows.h>
460 typedef SRWLOCK XMP_BasicRWLock;
461
462 #define XMP_BasicRWLock_Initialize(lck) InitializeSRWLock ( &lck )
463 #define XMP_BasicRWLock_Terminate(lck) /* Do nothing. */
464
465 #define XMP_BasicRWLock_AcquireForRead(lck) AcquireSRWLockShared ( &lck )
466 #define XMP_BasicRWLock_AcquireForWrite(lck) AcquireSRWLockExclusive ( &lck )
467
468 #define XMP_BasicRWLock_ReleaseFromRead(lck) ReleaseSRWLockShared ( &lck )
469 #define XMP_BasicRWLock_ReleaseFromWrite(lck) ReleaseSRWLockExclusive ( &lck )
470
471 #elif UseHomeGrownLock
472
473 class XMP_HomeGrownLock;
474 typedef XMP_HomeGrownLock XMP_BasicRWLock;
475
476 #define XMP_BasicRWLock_Initialize(lck) /* Do nothing. */
477 #define XMP_BasicRWLock_Terminate(lck) /* Do nothing. */
478 #define XMP_BasicRWLock_AcquireForRead(lck) lck.AcquireForRead()
479 #define XMP_BasicRWLock_AcquireForWrite(lck) lck.AcquireForWrite()
480 #define XMP_BasicRWLock_ReleaseFromRead(lck) lck.ReleaseFromRead()
481 #define XMP_BasicRWLock_ReleaseFromWrite(lck) lck.ReleaseFromWrite()
482
483 #if XMP_MacBuild | XMP_UNIXBuild | XMP_iOSBuild | XMP_AndroidBuild
484
485 #include <pthread.h>
486
487 typedef pthread_cond_t XMP_BasicQueue;
488
489 #elif XMP_WinBuild
490
491 #include <Windows.h>
492 #ifndef BuildLocksForWinXP
493 #define BuildLocksForWinXP 1
494 #endif
495
496 #if ! BuildLocksForWinXP
497 typedef CONDITION_VARIABLE XMP_BasicQueue; // ! Requires Vista or newer.
498 #else
499 class XMP_WinXP_HGQueue {
500 public:
501 XMP_WinXP_HGQueue();
502 ~XMP_WinXP_HGQueue();
503 void Wait ( XMP_BasicMutex & queueMutex );
504 void ReleaseOne();
505 void ReleaseAll();
506 private:
507 HANDLE queueEvent;
508 volatile XMP_Uns32 waitCount; // ! Does not need to be XMP_AtomicCounter.
509 volatile bool releaseAll;
510 };
511 typedef XMP_WinXP_HGQueue XMP_BasicQueue;
512 #endif
513
514 #endif
515
516 class XMP_HomeGrownLock {
517 public:
518 XMP_HomeGrownLock();
519 ~XMP_HomeGrownLock();
520 void AcquireForRead();
521 void AcquireForWrite();
522 void ReleaseFromRead();
523 void ReleaseFromWrite();
524 private:
525 XMP_BasicMutex queueMutex; // Used to protect queueing operations.
526 XMP_BasicQueue readerQueue, writerQueue;
527 volatile XMP_Uns32 lockCount, readersWaiting, writersWaiting; // ! Does not need to be XMP_AtomicCounter.
528 volatile bool beingWritten;
529 };
530
531 #else
532
533 #error "No locking mechanism chosen"
534
535 #endif
536
537 class XMP_ReadWriteLock { // For the lock objects, use XMP_AutoLock to do the locking.
538 public:
539 XMP_ReadWriteLock();
540 ~XMP_ReadWriteLock();
541 void Acquire ( bool forWriting );
542 void Release();
543 private:
544 XMP_BasicRWLock lock;
545 #if XMP_DebugBuild && HaveAtomicIncrDecr
546 volatile XMP_AtomicCounter lockCount; // ! Only for debug checks, must be XMP_AtomicCounter.
547 #endif
548 volatile bool beingWritten;
549 };
550
551 #define kXMP_ReadLock false
552 #define kXMP_WriteLock true
553
554 class XMP_AutoLock {
555 public:
556 XMP_AutoLock ( const XMP_ReadWriteLock * _lock, bool forWriting, bool cond = true ) : lock(0)
557 {
558 if ( cond ) {
559 // The cast below is needed because the _lock parameter might come from something
560 // like "const XMPMeta &", which would make the lock itself const. But we need to
561 // modify the lock (to acquire and release) even if the owning object is const.
562 this->lock = (XMP_ReadWriteLock*)_lock;
563 this->lock->Acquire ( forWriting );
564 }
565 }
566 ~XMP_AutoLock() { this->Release(); }
567 void Release() { if ( this->lock != 0 ) this->lock->Release(); this->lock = 0; }
568 private:
569 XMP_ReadWriteLock * lock;
570 XMP_AutoLock() {}; // ! Must not be used.
571 };
572
573 // =================================================================================================
574 // Support for wrappers
575 // ====================
576
577 #define AnnounceStaticEntry(proc) /* Do nothing. */
578 #define AnnounceObjectEntry(proc,rwMode) /* Do nothing. */
579
580 #define AnnounceExit() /* Do nothing. */
581
582 // -------------------------------------------------------------------------------------------------
583
584 #if UseGlobalLibraryLock
585 #define AcquireLibraryLock(lck) XMP_AutoMutex libLock ( &lck )
586 #else
587 #define AcquireLibraryLock(lck) /* nothing */
588 #endif
589
590 #define XMP_ENTER_NoLock(Proc) \
591 AnnounceStaticEntry ( Proc ); \
592 try { \
593 wResult->errMessage = 0;
594
595 #define XMP_ENTER_Static(Proc) \
596 AnnounceStaticEntry ( Proc ); \
597 AcquireLibraryLock ( sLibraryLock ); \
598 try { \
599 wResult->errMessage = 0;
600
601 #define XMP_ENTER_ObjRead(XMPClass,Proc) \
602 AnnounceObjectEntry ( Proc, "reader" ); \
603 AcquireLibraryLock ( sLibraryLock ); \
604 const XMPClass & thiz = *((XMPClass*)xmpObjRef); \
605 XMP_AutoLock objLock ( &thiz.lock, kXMP_ReadLock ); \
606 try { \
607 wResult->errMessage = 0;
608
609 #define XMP_ENTER_ObjWrite(XMPClass,Proc) \
610 AnnounceObjectEntry ( Proc, "writer" ); \
611 AcquireLibraryLock ( sLibraryLock ); \
612 XMPClass * thiz = (XMPClass*)xmpObjRef; \
613 XMP_AutoLock objLock ( &thiz->lock, kXMP_WriteLock ); \
614 try { \
615 wResult->errMessage = 0;
616
617 #define XMP_EXIT \
618 XMP_CATCH_EXCEPTIONS \
619 AnnounceExit();
620
621 #define XMP_EXIT_NoThrow \
622 } catch ( ... ) { \
623 AnnounceCatch ( "no-throw catch-all" ); \
624 /* Do nothing. */ \
625 } \
626 AnnounceExit();
627
628 #define XMP_CATCH_EXCEPTIONS \
629 } catch ( XMP_Error & xmpErr ) { \
630 wResult->int32Result = xmpErr.GetID(); \
631 wResult->ptrResult = (void*)"XMP"; \
632 wResult->errMessage = xmpErr.GetErrMsg(); \
633 if ( wResult->errMessage == 0 ) wResult->errMessage = ""; \
634 AnnounceCatch ( wResult->errMessage ); \
635 } catch ( std::exception & stdErr ) { \
636 wResult->int32Result = kXMPErr_StdException; \
637 wResult->errMessage = stdErr.what(); \
638 if ( wResult->errMessage == 0 ) wResult->errMessage = ""; \
639 AnnounceCatch ( wResult->errMessage ); \
640 } catch ( ... ) { \
641 wResult->int32Result = kXMPErr_UnknownException; \
642 wResult->errMessage = "Caught unknown exception"; \
643 AnnounceCatch ( wResult->errMessage ); \
644 }
645
646 #if XMP_DebugBuild
647 #define RELEASE_NO_THROW /* empty */
648 #else
649 #define RELEASE_NO_THROW throw()
650 #endif
651
652
653 #define NO_EXCEPT_FALSE noexcept(false)
654 #define NO_EXCEPT_TRUE noexcept(true)
655
656 // =================================================================================================
657 // Data structure dumping utilities
658 // ================================
659
660 #define IsHexDigit(ch) ( (('0' <= (ch)) && ((ch) <= '9')) || (('A' <= (ch)) && ((ch) <= 'F')) )
661 #define HexDigitValue(ch) ( (((ch) - '0') < 10) ? ((ch) - '0') : ((ch) - 'A' + 10) )
662
663 static const char * kTenSpaces = " ";
664 #define OutProcPadding(pad) { size_t padLen = (pad); \
665 for ( ; padLen >= 10; padLen -= 10 ) OutProcNChars ( kTenSpaces, 10 ); \
666 for ( ; padLen > 0; padLen -= 1 ) OutProcNChars ( " ", 1 ); }
667
668
669 #define OutProcNewline() { XMP_Status status = (*outProc) ( refCon, "\n", 1 ); if ( status != 0 ) return; }
670
671 #define OutProcNChars(p,n) { XMP_Status status = (*outProc) ( refCon, (p), (n) ); if ( status != 0 ) return; }
672
673 #define OutProcLiteral(lit) { XMP_Status _status = (*outProc) ( refCon, (lit), (XMP_StringLen)strlen(lit) ); if ( _status != 0 ) return; }
674
675 #define OutProcString(str) { XMP_Status _status = (*outProc) ( refCon, (str).c_str(), (XMP_StringLen)(str).size() ); if ( _status != 0 ) return; }
676
677 #define OutProcDecInt(num) { snprintf ( buffer, sizeof(buffer), "%ld", (long)(num) ); /* AUDIT: Using sizeof for snprintf length is safe */ \
678 buffer[sizeof(buffer) -1] = 0; /* AUDIT warning C6053: Make sure buffer is terminated */ \
679 XMP_Status _status = (*outProc) ( refCon, buffer, (XMP_StringLen)strlen(buffer) ); if ( _status != 0 ) return; }
680
681 #define OutProcHexInt(num) { snprintf ( buffer, sizeof(buffer), "%lX", (long)(num) ); /* AUDIT: Using sizeof for snprintf length is safe */ \
682 buffer[sizeof(buffer) -1] = 0; /* AUDIT warning C6053: Make sure buffer is terminated */ \
683 XMP_Status _status = (*outProc) ( refCon, buffer, (XMP_StringLen)strlen(buffer) ); if ( _status != 0 ) return; }
684
685 #define OutProcHexByte(num) { snprintf ( buffer, sizeof(buffer), "%.2X", (unsigned char)(num) ); /* AUDIT: Using sizeof for snprintf length is safe */ \
686 XMP_Status _status = (*outProc) ( refCon, buffer, (XMP_StringLen)strlen(buffer) ); if ( _status != 0 ) return; }
687
688 static const char * kIndent = " ";
689 #define OutProcIndent(lev) { for ( size_t i = 0; i < (lev); ++i ) OutProcNChars ( kIndent, 3 ); }
690
691 void DumpClearString ( const XMP_VarString & value, XMP_TextOutputProc outProc, void * refCon );
692
693 // =================================================================================================
694 // Namespace Tables
695 // ================
696 typedef std::vector <XMP_VarString> XMP_StringVector;
697 typedef XMP_StringVector::iterator XMP_StringVectorPos;
698 typedef XMP_StringVector::const_iterator XMP_StringVectorCPos;
699
700 typedef std::pair < XMP_VarString, XMP_VarString > XMP_StringPair;
701
702 typedef std::map < XMP_VarString, XMP_VarString > XMP_StringMap;
703 typedef XMP_StringMap::iterator XMP_StringMapPos;
704 typedef XMP_StringMap::const_iterator XMP_cStringMapPos;
705
706 class XMP_NamespaceTable {
707 public:
708
709 XMP_NamespaceTable() {};
710 XMP_NamespaceTable ( const XMP_NamespaceTable & presets );
711 virtual ~XMP_NamespaceTable() {};
712
713 bool Define ( XMP_StringPtr uri, XMP_StringPtr suggPrefix,
714 XMP_StringPtr * prefixPtr, XMP_StringLen * prefixLen);
715
716 bool GetPrefix ( XMP_StringPtr uri, XMP_StringPtr * prefixPtr, XMP_StringLen * prefixLen ) const;
717 bool GetURI ( XMP_StringPtr prefix, XMP_StringPtr * uriPtr, XMP_StringLen * uriLen ) const;
718
719 void Dump ( XMP_TextOutputProc outProc, void * refCon ) const;
720
721 private:
722
723 XMP_ReadWriteLock lock;
724 XMP_StringMap uriToPrefixMap, prefixToURIMap;
725
726 };
727
728
729 // Right now it supports only ^, $ and \d, in future we should use it as a wrapper over
730 // regex object once mac and Linux compilers start supporting them.
731
732 class XMP_RegExp {
733 public:
734 XMP_RegExp ( XMP_StringPtr regExp )
735 {
736 if ( regExp )
737 regExpStr = regExp;
738 }
739
740 XMP_Bool Match ( XMP_StringPtr s );
741
742 private:
743 XMP_VarString regExpStr;
744 };
745
746 // =================================================================================================
747
748 #endif // __XMP_LibUtils_hpp__