summaryrefslogtreecommitdiff
path: root/XMPFiles/source/PluginHandler/OS_Utils_Mac.cpp
blob: e3300a028d7da46f734c47716d355631c94ee529 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// =================================================================================================
// Copyright Adobe
// Copyright 2011 Adobe
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it. If you have received this file from a source other 
// than Adobe, then your use, modification, or distribution of it requires the prior written permission
// of Adobe.
// =================================================================================================

#include "ModuleUtils.h"
#include "source/UnicodeConversions.hpp"
#include "source/XIO.hpp"

#include <CoreFoundation/CFBundle.h>
#include <CoreFoundation/CFDate.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFError.h>
#include <string>


namespace XMP_PLUGIN
{

/** ************************************************************************************************************************
** Auto-releasing wrapper for Core Foundation objects
** AutoCFRef is an auto-releasing wrapper for any Core Foundation data type that can be passed
** to CFRetain and CFRelease. When constructed with a Core Foundation object, it is assumed it
** has just been created; that constructor does not call CFRetain. This supports reference counting
** through Core Foundation's own mechanism.
*/
template <class T>
class AutoCFRef
{
	
public:
	/// Default constructor creates NULL reference
	AutoCFRef()
		{
			mCFTypeRef = NULL;
		}
	
	/// Construct with any CFXXXRef type.
	explicit AutoCFRef(const T& value)
		{
			mCFTypeRef = value;
		}
	
	/// Copy constructor
	AutoCFRef(const AutoCFRef<T>& rhs)
		{
			mCFTypeRef = rhs.mCFTypeRef;
			if (mCFTypeRef)
				CFRetain(mCFTypeRef);
		}
	
	/// Destructor
	~AutoCFRef()
		{
			if (mCFTypeRef)
				CFRelease(mCFTypeRef);
		}
	
	/// Assignment operator
	void operator=(const AutoCFRef<T>& rhs)
		{
			if (!Same(rhs))
			{
				if (mCFTypeRef)
					CFRelease(mCFTypeRef);
				mCFTypeRef = rhs.mCFTypeRef;
				if (mCFTypeRef)
					CFRetain(mCFTypeRef);
			}
		}
	
	/// Equivalence operator
	/** operator== returns logical equivalence, the meaning of which varies from class to class
		in Core Foundation. See also AutoCFRef::Same.
		@param rhs The AutoCFRef<T> to compare to
		@return true if objects are logically equivalent.
	*/
	bool operator==(const AutoCFRef<T>& rhs) const
		{
			if (mCFTypeRef && rhs.mCFTypeRef)
				return CFEqual(mCFTypeRef, rhs.mCFTypeRef);
			else
				return mCFTypeRef == rhs.mCFTypeRef;
		}
	
	/// Non-equivalence operator
	/** operator!= returns logical equivalence, the meaning of which varies from class to class
		in Core Foundation. See also AutoCFRef::Same.
		@param rhs The AutoCFRef<T> to compare to
		@return true if objects are not logically equivalent.
	*/
	bool operator!=(const AutoCFRef<T>& rhs) const
		{
			return !operator==(rhs);
		}
	
	/// References same CF object
	/** Same returns true if both objects reference the same CF object (or both are NULL).
		For logical equivalence (CFEqual) use == operator.
		@param rhs The AutoCFRef<T> to compare to
		@return true if AutoRefs reference the same object.
	*/
	bool Same(const AutoCFRef<T>& rhs) const
		{
			return mCFTypeRef == rhs.mCFTypeRef;
		}
		
	/// Change the object referenced
	/** Reset is used to put a new CF object into a preexisting AutoCFRef. Does NOT call CFRetain,
		so if its ref count is 1 on entry, it will delete on destruction, barring other influences.
		@param value (optional) the new CFXXXRef to set, default is NULL.
	*/
	void Reset(T value = NULL)
		{
			if (value != mCFTypeRef)
			{
				if (mCFTypeRef)
					CFRelease(mCFTypeRef);
				mCFTypeRef = value;
			}
		}
	
	/// Return true if no object referenced.
	bool IsNull() const
		{
			return mCFTypeRef == NULL;
		}
	
	/// Return retain count.
	/** Returns retain count of referenced object from Core Foundation. Can be used to track down
		failures in reference management, but be aware that some objects might be returned to your
		code by the operating system with a retain count already greater than one.
		@return Referenced object's retain count.
	*/
	CFIndex RetainCount()
		{
			return mCFTypeRef ? CFGetRetainCount(mCFTypeRef) : 0;
		}
	
	/// Const dereference operator
	/** operator* returns a reference to the contained CFTypeRef. Use this to pass the object into
		Core Foundation functions. DO NOT use this to create a new AutoCFRef; copy construct instead.
	*/
	const T& operator*() const
		{
			return mCFTypeRef;
		}

	/// Nonconst dereference operator
	/** operator* returns a reference to the contained CFTypeRef. Use this to pass the object into
		Core Foundation functions. DO NOT use this to create a new AutoCFRef; copy construct instead.
	*/
	T& operator*()
		{
			return mCFTypeRef;
		}

private:
	T			mCFTypeRef;
};

typedef AutoCFRef<CFURLRef>					AutoCFURL;
typedef AutoCFRef<CFStringRef>				AutoCFString;

/** ************************************************************************************************************************
** Convert string into CFString
*/
static inline CFStringRef MakeCFString(const std::string& inString, CFStringEncoding inEncoding = kCFStringEncodingUTF8)
{
	CFStringRef str = ::CFStringCreateWithCString( NULL, inString.c_str(), inEncoding );
	return str;
}

bool IsValidLibrary( const std::string & inModulePath )
{
	bool result = false;
	AutoCFURL bundleURL(::CFURLCreateFromFileSystemRepresentation(
		kCFAllocatorDefault,
		(const UInt8*) inModulePath.c_str(),
		inModulePath.size(),
		false));
	if (*bundleURL != NULL)
	{
		CFBundleRef bundle = ::CFBundleCreate(kCFAllocatorDefault, *bundleURL);
		if (bundle != NULL)
		{
			CFArrayRef arrayRef = ::CFBundleCopyExecutableArchitectures(bundle);
			if (arrayRef != NULL)
			{
				result = true;
				::CFRelease(arrayRef);
			}

			::CFRelease(bundle);
		}
	}		
	return result;
}

OS_ModuleRef LoadModule( const std::string & inModulePath, bool inOnlyResourceAccess )
{
	OS_ModuleRef result = NULL;
	AutoCFURL bundleURL(::CFURLCreateFromFileSystemRepresentation(
		kCFAllocatorDefault,
		(const UInt8*) inModulePath.c_str(),
		inModulePath.size(),
		false));
	if (*bundleURL != NULL)
	{
		result = ::CFBundleCreate(kCFAllocatorDefault, *bundleURL);
		if (!inOnlyResourceAccess && (result != NULL))
		{
			::CFErrorRef errorRef = NULL;
			Boolean loaded = ::CFBundleIsExecutableLoaded(result);
			if (!loaded)
			{
				loaded = ::CFBundleLoadExecutableAndReturnError(result, &errorRef);
				if(!loaded || errorRef != NULL)
				{
					::CFRelease(errorRef);
					// release bundle and return NULL
					::CFRelease(result);
					result = NULL;
					throw XMP_Error( kXMPErr_InternalFailure, "Failed to load module" );
				}
			}
		}
	}
	return result;
}

void UnloadModule( OS_ModuleRef inModule, bool inOnlyResourceAccess )
{
	if (inModule != NULL)
	{
		::CFRelease(inModule);
	}
}

void* GetFunctionPointerFromModuleImpl(	OS_ModuleRef inOSModule, const char* inSymbol )
{
	void* proc = NULL;
	if( inOSModule != NULL)
	{
		proc = ::CFBundleGetFunctionPointerForName( inOSModule, *AutoCFString(MakeCFString(inSymbol)) );
	}
	return proc;
}

bool GetResourceDataFromModule(
	OS_ModuleRef inOSModule,
	const std::string & inResourceName,
	const std::string & inResourceType,
	std::string & outBuffer)
{
	bool success = false;
	bool inSearchInSubFolderWithNameOfResourceType = false;
	AutoCFString resourceName( MakeCFString( inResourceName ) );
	AutoCFString resourceType( MakeCFString( inResourceType ) );
	AutoCFString subfolderName( inSearchInSubFolderWithNameOfResourceType ? MakeCFString( inResourceType ) : nil );

	AutoCFURL url( ::CFBundleCopyResourceURL( inOSModule, *resourceName, *resourceType, *subfolderName ) );

	if ( !url.IsNull() )
	{
		typedef AutoCFRef<CFNumberRef> AutoCFNumber;
		typedef AutoCFRef<CFErrorRef> AutoCFError;
		typedef AutoCFRef<CFReadStreamRef> AutoCFReadStream;
		AutoCFError cfError;
		AutoCFNumber length;

		if ( ::CFURLCopyResourcePropertyForKey(*url, kCFURLFileSizeKey, &length, &(*cfError)) && !length.IsNull())
		{
			SInt64 sizeOfFile = 0;
			success = ::CFNumberGetValue( *length, kCFNumberSInt64Type, &sizeOfFile );

			// presumingly we don't want to load more than 2GByte at once (!)
			if ( success && sizeOfFile != 0 && sizeOfFile < std::numeric_limits<XMP_Int32>::max() )
			{
				AutoCFReadStream readStream(::CFReadStreamCreateWithFile(kCFAllocatorDefault, *url));
				if( *readStream != NULL && CFReadStreamOpen(*readStream) )
				{
					outBuffer.assign(sizeOfFile, NULL);
					success = ( ::CFReadStreamRead(*readStream,reinterpret_cast< UInt8 * > (&outBuffer[0]), sizeOfFile) != -1 );
					::CFReadStreamClose(*readStream);
					return success;
				}
			}
		}
	}

	return false;
}

} //namespace XMP_PLUGIN