blob: c95e491b769824f8270be5bce98c5ad9f578d576 [file] [log] [blame]
shess5f2c3442017-01-24 02:15:101// Copyright (c) 2017 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "sql/vfs_wrapper.h"
6
7#include <algorithm>
8#include <string>
9#include <vector>
10
11#include "base/debug/leak_annotations.h"
12#include "base/logging.h"
13#include "base/memory/ptr_util.h"
shess3998fbc2017-03-15 16:18:3114#include "base/metrics/histogram_macros.h"
shess5f2c3442017-01-24 02:15:1015#include "base/strings/string_piece.h"
16
17#if defined(OS_MACOSX) && !defined(OS_IOS)
18#include <CoreFoundation/CoreFoundation.h>
19#include <CoreServices/CoreServices.h>
20
21#include "base/mac/mac_util.h"
22#include "base/mac/scoped_cftyperef.h"
23#endif
24
25namespace sql {
26namespace {
27
28// https://www.sqlite.org/vfs.html - documents the overall VFS system.
29//
30// https://www.sqlite.org/c3ref/vfs.html - VFS methods. This code tucks the
31// wrapped VFS pointer into the wrapper's pAppData pointer.
32//
33// https://www.sqlite.org/c3ref/file.html - instance of an open file. This code
34// allocates a VfsFile for this, which contains a pointer to the wrapped file.
35// Idiomatic SQLite would take the wrapped VFS szOsFile and increase it to store
36// additional data as a prefix.
37
38sqlite3_vfs* GetWrappedVfs(sqlite3_vfs* wrapped_vfs) {
39 return static_cast<sqlite3_vfs*>(wrapped_vfs->pAppData);
40}
41
42// NOTE(shess): This structure is allocated by SQLite using malloc. Do not add
43// C++ objects, they will not be correctly constructed and destructed. Instead,
44// manually manage a pointer to a C++ object in Open() and Close().
45struct VfsFile {
46 const sqlite3_io_methods* methods;
47 sqlite3_file* wrapped_file;
48};
49
50VfsFile* AsVfsFile(sqlite3_file* wrapper_file) {
51 return reinterpret_cast<VfsFile*>(wrapper_file);
52}
53
54sqlite3_file* GetWrappedFile(sqlite3_file* wrapper_file) {
55 return AsVfsFile(wrapper_file)->wrapped_file;
56}
57
58int Close(sqlite3_file* sqlite_file)
59{
60 VfsFile* file = AsVfsFile(sqlite_file);
61
62 int r = file->wrapped_file->pMethods->xClose(file->wrapped_file);
63 sqlite3_free(file->wrapped_file);
64 memset(file, '\0', sizeof(*file));
65 return r;
66}
67
68int Read(sqlite3_file* sqlite_file, void* buf, int amt, sqlite3_int64 ofs)
69{
70 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
71 return wrapped_file->pMethods->xRead(wrapped_file, buf, amt, ofs);
72}
73
74int Write(sqlite3_file* sqlite_file, const void* buf, int amt,
75 sqlite3_int64 ofs)
76{
77 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
78 return wrapped_file->pMethods->xWrite(wrapped_file, buf, amt, ofs);
79}
80
81int Truncate(sqlite3_file* sqlite_file, sqlite3_int64 size)
82{
83 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
84 return wrapped_file->pMethods->xTruncate(wrapped_file, size);
85}
86
87int Sync(sqlite3_file* sqlite_file, int flags)
88{
89 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
90 return wrapped_file->pMethods->xSync(wrapped_file, flags);
91}
92
93int FileSize(sqlite3_file* sqlite_file, sqlite3_int64* size)
94{
95 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
96 return wrapped_file->pMethods->xFileSize(wrapped_file, size);
97}
98
99int Lock(sqlite3_file* sqlite_file, int file_lock)
100{
101 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
102 return wrapped_file->pMethods->xLock(wrapped_file, file_lock);
103}
104
105int Unlock(sqlite3_file* sqlite_file, int file_lock)
106{
107 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
108 return wrapped_file->pMethods->xUnlock(wrapped_file, file_lock);
109}
110
111int CheckReservedLock(sqlite3_file* sqlite_file, int* result)
112{
113 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
114 return wrapped_file->pMethods->xCheckReservedLock(wrapped_file, result);
115}
116
117int FileControl(sqlite3_file* sqlite_file, int op, void* arg)
118{
119 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
120 return wrapped_file->pMethods->xFileControl(wrapped_file, op, arg);
121}
122
123int SectorSize(sqlite3_file* sqlite_file)
124{
125 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
126 return wrapped_file->pMethods->xSectorSize(wrapped_file);
127}
128
129int DeviceCharacteristics(sqlite3_file* sqlite_file)
130{
131 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
132 return wrapped_file->pMethods->xDeviceCharacteristics(wrapped_file);
133}
134
135int ShmMap(sqlite3_file *sqlite_file, int region, int size,
136 int extend, void volatile **pp) {
137 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
138 return wrapped_file->pMethods->xShmMap(
139 wrapped_file, region, size, extend, pp);
140}
141
142int ShmLock(sqlite3_file *sqlite_file, int ofst, int n, int flags) {
143 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
144 return wrapped_file->pMethods->xShmLock(wrapped_file, ofst, n, flags);
145}
146
147void ShmBarrier(sqlite3_file *sqlite_file) {
148 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
149 wrapped_file->pMethods->xShmBarrier(wrapped_file);
150}
151
152int ShmUnmap(sqlite3_file *sqlite_file, int del) {
153 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
154 return wrapped_file->pMethods->xShmUnmap(wrapped_file, del);
155}
156
157int Fetch(sqlite3_file *sqlite_file, sqlite3_int64 off, int amt, void **pp) {
158 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
159 return wrapped_file->pMethods->xFetch(wrapped_file, off, amt, pp);
160}
161
162int Unfetch(sqlite3_file *sqlite_file, sqlite3_int64 off, void *p) {
163 sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
164 return wrapped_file->pMethods->xUnfetch(wrapped_file, off, p);
165}
166
167#if defined(OS_MACOSX) && !defined(OS_IOS)
168// Helper to convert a POSIX path into a CoreFoundation path.
169base::ScopedCFTypeRef<CFURLRef> CFURLRefForPath(const char* path){
170 base::ScopedCFTypeRef<CFStringRef> urlString(
171 CFStringCreateWithFileSystemRepresentation(kCFAllocatorDefault, path));
172 base::ScopedCFTypeRef<CFURLRef> url(
173 CFURLCreateWithFileSystemPath(kCFAllocatorDefault, urlString,
174 kCFURLPOSIXPathStyle, FALSE));
175 return url;
176}
177#endif
178
179int Open(sqlite3_vfs* vfs, const char* file_name, sqlite3_file* wrapper_file,
180 int desired_flags, int* used_flags) {
181 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
182
183 sqlite3_file* wrapped_file = static_cast<sqlite3_file*>(
184 sqlite3_malloc(wrapped_vfs->szOsFile));
185 if (!wrapped_file)
186 return SQLITE_NOMEM;
187
188 // NOTE(shess): SQLite's unixOpen() makes assumptions about the structure of
189 // |file_name|. Do not pass a local copy, here, only the passed-in value.
190 int rc = wrapped_vfs->xOpen(wrapped_vfs,
191 file_name, wrapped_file,
192 desired_flags, used_flags);
193 if (rc != SQLITE_OK) {
194 sqlite3_free(wrapped_file);
195 return rc;
196 }
197 // NOTE(shess): Any early exit from here needs to call xClose() on
198 // |wrapped_file|.
199
200#if defined(OS_MACOSX) && !defined(OS_IOS)
201 // When opening journal files, propagate time-machine exclusion from db.
202 static int kJournalFlags =
203 SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_TEMP_JOURNAL |
204 SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_MASTER_JOURNAL;
205 if (file_name && (desired_flags & kJournalFlags)) {
206 // https://www.sqlite.org/c3ref/vfs.html indicates that the journal path
207 // will have a "-suffix".
208 size_t dash_index = base::StringPiece(file_name).rfind('-');
209 if (dash_index != base::StringPiece::npos) {
210 std::string db_name(file_name, dash_index);
211 base::ScopedCFTypeRef<CFURLRef> db_url(CFURLRefForPath(db_name.c_str()));
212 if (CSBackupIsItemExcluded(db_url, nullptr)) {
213 base::ScopedCFTypeRef<CFURLRef> journal_url(CFURLRefForPath(file_name));
214 CSBackupSetItemExcluded(journal_url, TRUE, FALSE);
215 }
216 }
217 }
218#endif
219
Victor Costan86ca4312018-02-07 21:34:10220 // |iVersion| determines what methods SQLite may call on the instance.
221 // Having the methods which can't be proxied return an error may cause SQLite
222 // to operate differently than if it didn't call those methods at all. To be
223 // on the safe side, the wrapper sqlite3_io_methods version perfectly matches
224 // the version of the wrapped files.
shess5f2c3442017-01-24 02:15:10225 //
Victor Costan86ca4312018-02-07 21:34:10226 // At a first glance, it might be tempting to simplify the code by
227 // restricting wrapping support to VFS version 3. However, this would fail
228 // on Fuchsia and might fail on Mac.
229 //
230 // On Mac, SQLite built with SQLITE_ENABLE_LOCKING_STYLE ends up using a VFS
231 // that dynamically dispatches between a few variants of sqlite3_io_methods,
232 // based on whether the opened database is on a local or on a remote (AFS,
233 // NFS) filesystem. Some variants return a VFS version 1 structure.
234 //
235 // Fuchsia doesn't implement POSIX locking, so it always uses dot-style
236 // locking, which returns VFS version 1 files.
shess5f2c3442017-01-24 02:15:10237 VfsFile* file = AsVfsFile(wrapper_file);
238 file->wrapped_file = wrapped_file;
239 if (wrapped_file->pMethods->iVersion == 1) {
240 static const sqlite3_io_methods io_methods = {
241 1,
242 Close,
243 Read,
244 Write,
245 Truncate,
246 Sync,
247 FileSize,
248 Lock,
249 Unlock,
250 CheckReservedLock,
251 FileControl,
252 SectorSize,
253 DeviceCharacteristics,
254 };
255 file->methods = &io_methods;
256 } else if (wrapped_file->pMethods->iVersion == 2) {
257 static const sqlite3_io_methods io_methods = {
258 2,
259 Close,
260 Read,
261 Write,
262 Truncate,
263 Sync,
264 FileSize,
265 Lock,
266 Unlock,
267 CheckReservedLock,
268 FileControl,
269 SectorSize,
270 DeviceCharacteristics,
271 // Methods above are valid for version 1.
272 ShmMap,
273 ShmLock,
274 ShmBarrier,
275 ShmUnmap,
276 };
277 file->methods = &io_methods;
278 } else {
279 static const sqlite3_io_methods io_methods = {
280 3,
281 Close,
282 Read,
283 Write,
284 Truncate,
285 Sync,
286 FileSize,
287 Lock,
288 Unlock,
289 CheckReservedLock,
290 FileControl,
291 SectorSize,
292 DeviceCharacteristics,
293 // Methods above are valid for version 1.
294 ShmMap,
295 ShmLock,
296 ShmBarrier,
297 ShmUnmap,
298 // Methods above are valid for version 2.
299 Fetch,
300 Unfetch,
301 };
302 file->methods = &io_methods;
303 }
304 return SQLITE_OK;
305}
306
307int Delete(sqlite3_vfs* vfs, const char* file_name, int sync_dir) {
308 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
309 return wrapped_vfs->xDelete(wrapped_vfs, file_name, sync_dir);
310}
311
312int Access(sqlite3_vfs* vfs, const char* file_name, int flag, int* res) {
313 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
314 return wrapped_vfs->xAccess(wrapped_vfs, file_name, flag, res);
315}
316
317int FullPathname(sqlite3_vfs* vfs, const char* relative_path,
318 int buf_size, char* absolute_path) {
shess5f2c3442017-01-24 02:15:10319 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
320 return wrapped_vfs->xFullPathname(
321 wrapped_vfs, relative_path, buf_size, absolute_path);
322}
323
324void* DlOpen(sqlite3_vfs* vfs, const char* filename) {
325 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
326 return wrapped_vfs->xDlOpen(wrapped_vfs, filename);
327}
328
329void DlError(sqlite3_vfs* vfs, int buf_size, char* error_buffer) {
330 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
331 wrapped_vfs->xDlError(wrapped_vfs, buf_size, error_buffer);
332}
333
334void(*DlSym(sqlite3_vfs* vfs, void* handle, const char* sym))(void) {
335 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
336 return wrapped_vfs->xDlSym(wrapped_vfs, handle, sym);
337}
338
339void DlClose(sqlite3_vfs* vfs, void* handle) {
340 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
341 wrapped_vfs->xDlClose(wrapped_vfs, handle);
342}
343
344int Randomness(sqlite3_vfs* vfs, int buf_size, char* buffer) {
345 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
346 return wrapped_vfs->xRandomness(wrapped_vfs, buf_size, buffer);
347}
348
349int Sleep(sqlite3_vfs* vfs, int microseconds) {
350 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
351 return wrapped_vfs->xSleep(wrapped_vfs, microseconds);
352}
353
354int CurrentTime(sqlite3_vfs* vfs, double* now) {
355 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
356 return wrapped_vfs->xCurrentTime(wrapped_vfs, now);
357}
358
359int GetLastError(sqlite3_vfs* vfs, int e, char* s) {
360 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
361 return wrapped_vfs->xGetLastError(wrapped_vfs, e, s);
362}
363
364int CurrentTimeInt64(sqlite3_vfs* vfs, sqlite3_int64* now) {
365 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
366 return wrapped_vfs->xCurrentTimeInt64(wrapped_vfs, now);
367}
368
369int SetSystemCall(sqlite3_vfs* vfs, const char* name,
370 sqlite3_syscall_ptr func) {
371 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
372 return wrapped_vfs->xSetSystemCall(wrapped_vfs, name, func);
373}
374
375sqlite3_syscall_ptr GetSystemCall(sqlite3_vfs* vfs, const char* name) {
376 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
377 return wrapped_vfs->xGetSystemCall(wrapped_vfs, name);
378}
379
380const char* NextSystemCall(sqlite3_vfs* vfs, const char* name) {
381 sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
382 return wrapped_vfs->xNextSystemCall(wrapped_vfs, name);
383}
384
385} // namespace
386
387sqlite3_vfs* VFSWrapper() {
388 const char* kVFSName = "VFSWrapper";
389
390 // Return existing version if already registered.
391 {
392 sqlite3_vfs* vfs = sqlite3_vfs_find(kVFSName);
393 if (vfs != nullptr)
394 return vfs;
395 }
396
397 // Get the default VFS for this platform. If no default VFS, give up.
398 sqlite3_vfs* wrapped_vfs = sqlite3_vfs_find(nullptr);
399 if (!wrapped_vfs)
400 return nullptr;
401
402 std::unique_ptr<sqlite3_vfs, std::function<void(sqlite3_vfs*)>> wrapper_vfs(
403 static_cast<sqlite3_vfs*>(sqlite3_malloc(sizeof(sqlite3_vfs))),
404 [](sqlite3_vfs* v) {
405 sqlite3_free(v);
406 });
407 memset(wrapper_vfs.get(), '\0', sizeof(sqlite3_vfs));
408
409 // VFS implementations should always work with a SQLite that only knows about
410 // earlier versions.
411 wrapper_vfs->iVersion = std::min(wrapped_vfs->iVersion, 3);
412
413 // Caller of xOpen() allocates this much space.
414 wrapper_vfs->szOsFile = sizeof(VfsFile);
415
416 wrapper_vfs->mxPathname = wrapped_vfs->mxPathname;
417 wrapper_vfs->pNext = nullptr;
418 wrapper_vfs->zName = kVFSName;
419
420 // Keep a reference to the wrapped vfs for use in methods.
421 wrapper_vfs->pAppData = wrapped_vfs;
422
423 // VFS methods.
424 wrapper_vfs->xOpen = &Open;
425 wrapper_vfs->xDelete = &Delete;
426 wrapper_vfs->xAccess = &Access;
427 wrapper_vfs->xFullPathname = &FullPathname;
428 wrapper_vfs->xDlOpen = &DlOpen;
429 wrapper_vfs->xDlError = &DlError;
430 wrapper_vfs->xDlSym = &DlSym;
431 wrapper_vfs->xDlClose = &DlClose;
432 wrapper_vfs->xRandomness = &Randomness;
433 wrapper_vfs->xSleep = &Sleep;
Victor Costana0905fab2018-01-30 18:48:50434 // |xCurrentTime| is null when SQLite is built with SQLITE_OMIT_DEPRECATED.
435 wrapper_vfs->xCurrentTime =
436 (wrapped_vfs->xCurrentTime ? &CurrentTime : nullptr);
shess5f2c3442017-01-24 02:15:10437 wrapper_vfs->xGetLastError = &GetLastError;
438 // The methods above are in version 1 of sqlite_vfs.
Victor Costan86ca4312018-02-07 21:34:10439 DCHECK(wrapped_vfs->xCurrentTimeInt64);
440 wrapper_vfs->xCurrentTimeInt64 = &CurrentTimeInt64;
shess5f2c3442017-01-24 02:15:10441 // The methods above are in version 2 of sqlite_vfs.
Victor Costan86ca4312018-02-07 21:34:10442 DCHECK(wrapped_vfs->xSetSystemCall);
shess5f2c3442017-01-24 02:15:10443 wrapper_vfs->xSetSystemCall = &SetSystemCall;
Victor Costan86ca4312018-02-07 21:34:10444 DCHECK(wrapped_vfs->xGetSystemCall);
shess5f2c3442017-01-24 02:15:10445 wrapper_vfs->xGetSystemCall = &GetSystemCall;
Victor Costan86ca4312018-02-07 21:34:10446 DCHECK(wrapped_vfs->xNextSystemCall);
shess5f2c3442017-01-24 02:15:10447 wrapper_vfs->xNextSystemCall = &NextSystemCall;
448 // The methods above are in version 3 of sqlite_vfs.
449
450 if (SQLITE_OK == sqlite3_vfs_register(wrapper_vfs.get(), 0)) {
451 ANNOTATE_LEAKING_OBJECT_PTR(wrapper_vfs.get());
452 wrapper_vfs.release();
453 }
454
455 return sqlite3_vfs_find(kVFSName);
456}
457
458} // namespace sql