3737#include "crypto.h"
3838#ifndef OMIT_MEMLOCK
3939#if defined(__unix__ ) || defined(__APPLE__ ) || defined(_AIX )
40+ #include <errno.h>
41+ #include <unistd.h>
42+ #include <sys/resource.h>
4043#include <sys/mman.h>
4144#elif defined(_WIN32 )
42- # include <windows.h>
45+ #include <windows.h>
4346#endif
4447#endif
4548
@@ -248,14 +251,28 @@ int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
248251void sqlcipher_free (void * ptr , int sz ) {
249252 if (ptr ) {
250253 if (sz > 0 ) {
254+ #ifndef OMIT_MEMLOCK
255+ int rc ;
256+ #if defined(__unix__ ) || defined(__APPLE__ )
257+ unsigned long pagesize = sysconf (_SC_PAGESIZE );
258+ unsigned long offset = (unsigned long ) ptr % pagesize ;
259+ #endif
260+ #endif
251261 CODEC_TRACE ("sqlcipher_free: calling sqlcipher_memset(%p,0,%d)\n" , ptr , sz );
252262 sqlcipher_memset (ptr , 0 , sz );
253263#ifndef OMIT_MEMLOCK
254264#if defined(__unix__ ) || defined(__APPLE__ )
255- munlock (ptr , sz );
265+ CODEC_TRACE ("sqlcipher_free: calling munlock(%p,%lu)\n" , ptr - offset , sz + offset );
266+ rc = munlock (ptr - offset , sz + offset );
267+ if (rc != 0 ) {
268+ CODEC_TRACE ("sqlcipher_free: munlock(%p,%lu) returned %d errno=%d\n" , ptr - offset , sz + offset , rc , errno );
269+ }
256270#elif defined(_WIN32 )
257271#if !(defined(WINAPI_FAMILY ) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP ))
258- VirtualUnlock (ptr , sz );
272+ rc = VirtualUnlock (ptr , sz );
273+ if (!rc ) {
274+ CODEC_TRACE ("sqlcipher_free: VirtualUnlock(%p,%d) returned %d LastError=%d\n" , ptr , sz , rc , GetLastError ());
275+ }
259276#endif
260277#endif
261278#endif
@@ -277,11 +294,21 @@ void* sqlcipher_malloc(int sz) {
277294 sqlcipher_memset (ptr , 0 , sz );
278295#ifndef OMIT_MEMLOCK
279296 if (ptr ) {
297+ int rc ;
280298#if defined(__unix__ ) || defined(__APPLE__ )
281- mlock (ptr , sz );
299+ unsigned long pagesize = sysconf (_SC_PAGESIZE );
300+ unsigned long offset = (unsigned long ) ptr % pagesize ;
301+ CODEC_TRACE ("sqlcipher_malloc: calling mlock(%p,%lu); _SC_PAGESIZE=%lu\n" , ptr - offset , sz + offset , pagesize );
302+ rc = mlock (ptr - offset , sz + offset );
303+ if (rc != 0 ) {
304+ CODEC_TRACE ("sqlcipher_malloc: mlock(%p,%lu) returned %d errno=%d\n" , ptr - offset , sz + offset , rc , errno );
305+ }
282306#elif defined(_WIN32 )
283307#if !(defined(WINAPI_FAMILY ) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP ))
284- VirtualLock (ptr , sz );
308+ rc = VirtualLock (ptr , sz );
309+ if (rc == 0 ) {
310+ CODEC_TRACE ("sqlcipher_malloc: VirtualLock(%p,%d) returned %d LastError=%d\n" , ptr , sz , rc , GetLastError ());
311+ }
285312#endif
286313#endif
287314 }
0 commit comments