Feat: runtime profile override with getenv
[platform/framework/web/chromium-efl.git] / sql / vfs_wrapper.cc
1 // Copyright 2017 The Chromium Authors
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/check_op.h"
12 #include "base/debug/leak_annotations.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/ptr_util.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/notreached.h"
17 #include "base/strings/string_piece.h"
18 #include "build/build_config.h"
19
20 #if BUILDFLAG(IS_APPLE)
21 #include "base/apple/backup_util.h"
22 #endif
23
24 #if BUILDFLAG(IS_FUCHSIA)
25 #include "sql/vfs_wrapper_fuchsia.h"
26 #endif
27
28 namespace sql {
29 namespace {
30
31 // https://www.sqlite.org/vfs.html - documents the overall VFS system.
32 //
33 // https://www.sqlite.org/c3ref/vfs.html - VFS methods.  This code tucks the
34 // wrapped VFS pointer into the wrapper's pAppData pointer.
35 //
36 // https://www.sqlite.org/c3ref/file.html - instance of an open file.  This code
37 // allocates a VfsFile for this, which contains a pointer to the wrapped file.
38 // Idiomatic SQLite would take the wrapped VFS szOsFile and increase it to store
39 // additional data as a prefix.
40
41 sqlite3_vfs* GetWrappedVfs(sqlite3_vfs* wrapped_vfs) {
42   return static_cast<sqlite3_vfs*>(wrapped_vfs->pAppData);
43 }
44
45 VfsFile* AsVfsFile(sqlite3_file* wrapper_file) {
46   return reinterpret_cast<VfsFile*>(wrapper_file);
47 }
48
49 sqlite3_file* GetWrappedFile(sqlite3_file* wrapper_file) {
50   return AsVfsFile(wrapper_file)->wrapped_file;
51 }
52
53 int Close(sqlite3_file* sqlite_file) {
54 #if BUILDFLAG(IS_FUCHSIA)
55   // Other platforms automatically unlock when the file descriptor is closed,
56   // but the fuchsia virtual implementation doesn't have that so it needs an
57   // explicit unlock on close.
58   Unlock(sqlite_file, SQLITE_LOCK_NONE);
59 #endif
60
61   VfsFile* file = AsVfsFile(sqlite_file);
62   int r = file->wrapped_file->pMethods->xClose(file->wrapped_file);
63   sqlite3_free(file->wrapped_file);
64
65   // Memory will be freed with sqlite3_free(), so the destructor needs to be
66   // called explicitly.
67   file->~VfsFile();
68   memset(file, '\0', sizeof(*file));
69   return r;
70 }
71
72 int Read(sqlite3_file* sqlite_file, void* buf, int amt, sqlite3_int64 ofs)
73 {
74   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
75   return wrapped_file->pMethods->xRead(wrapped_file, buf, amt, ofs);
76 }
77
78 int Write(sqlite3_file* sqlite_file, const void* buf, int amt,
79           sqlite3_int64 ofs)
80 {
81   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
82   return wrapped_file->pMethods->xWrite(wrapped_file, buf, amt, ofs);
83 }
84
85 int Truncate(sqlite3_file* sqlite_file, sqlite3_int64 size)
86 {
87   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
88   return wrapped_file->pMethods->xTruncate(wrapped_file, size);
89 }
90
91 int Sync(sqlite3_file* sqlite_file, int flags)
92 {
93   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
94   return wrapped_file->pMethods->xSync(wrapped_file, flags);
95 }
96
97 int FileSize(sqlite3_file* sqlite_file, sqlite3_int64* size)
98 {
99   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
100   return wrapped_file->pMethods->xFileSize(wrapped_file, size);
101 }
102
103 #if !BUILDFLAG(IS_FUCHSIA)
104
105 int Lock(sqlite3_file* sqlite_file, int file_lock)
106 {
107   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
108   return wrapped_file->pMethods->xLock(wrapped_file, file_lock);
109 }
110
111 int Unlock(sqlite3_file* sqlite_file, int file_lock)
112 {
113   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
114   return wrapped_file->pMethods->xUnlock(wrapped_file, file_lock);
115 }
116
117 int CheckReservedLock(sqlite3_file* sqlite_file, int* result)
118 {
119   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
120   return wrapped_file->pMethods->xCheckReservedLock(wrapped_file, result);
121 }
122
123 #endif  // !BUILDFLAG(IS_FUCHSIA)
124 // Else these functions are imported via vfs_wrapper_fuchsia.h.
125
126 int FileControl(sqlite3_file* sqlite_file, int op, void* arg)
127 {
128   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
129   return wrapped_file->pMethods->xFileControl(wrapped_file, op, arg);
130 }
131
132 int SectorSize(sqlite3_file* sqlite_file)
133 {
134   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
135   return wrapped_file->pMethods->xSectorSize(wrapped_file);
136 }
137
138 int DeviceCharacteristics(sqlite3_file* sqlite_file)
139 {
140   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
141   return wrapped_file->pMethods->xDeviceCharacteristics(wrapped_file);
142 }
143
144 int ShmMap(sqlite3_file *sqlite_file, int region, int size,
145            int extend, void volatile **pp) {
146   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
147   return wrapped_file->pMethods->xShmMap(
148       wrapped_file, region, size, extend, pp);
149 }
150
151 int ShmLock(sqlite3_file *sqlite_file, int ofst, int n, int flags) {
152   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
153   return wrapped_file->pMethods->xShmLock(wrapped_file, ofst, n, flags);
154 }
155
156 void ShmBarrier(sqlite3_file *sqlite_file) {
157   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
158   wrapped_file->pMethods->xShmBarrier(wrapped_file);
159 }
160
161 int ShmUnmap(sqlite3_file *sqlite_file, int del) {
162   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
163   return wrapped_file->pMethods->xShmUnmap(wrapped_file, del);
164 }
165
166 int Fetch(sqlite3_file *sqlite_file, sqlite3_int64 off, int amt, void **pp) {
167   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
168   return wrapped_file->pMethods->xFetch(wrapped_file, off, amt, pp);
169 }
170
171 int Unfetch(sqlite3_file *sqlite_file, sqlite3_int64 off, void *p) {
172   sqlite3_file* wrapped_file = GetWrappedFile(sqlite_file);
173   return wrapped_file->pMethods->xUnfetch(wrapped_file, off, p);
174 }
175
176 int Open(sqlite3_vfs* vfs, const char* file_name, sqlite3_file* wrapper_file,
177          int desired_flags, int* used_flags) {
178   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
179
180   sqlite3_file* wrapped_file = static_cast<sqlite3_file*>(
181       sqlite3_malloc(wrapped_vfs->szOsFile));
182   if (!wrapped_file)
183     return SQLITE_NOMEM;
184
185   // NOTE(shess): SQLite's unixOpen() makes assumptions about the structure of
186   // |file_name|.  Do not pass a local copy, here, only the passed-in value.
187   int rc = wrapped_vfs->xOpen(wrapped_vfs,
188                               file_name, wrapped_file,
189                               desired_flags, used_flags);
190   if (rc != SQLITE_OK) {
191     sqlite3_free(wrapped_file);
192     return rc;
193   }
194   // NOTE(shess): Any early exit from here needs to call xClose() on
195   // |wrapped_file|.
196
197 #if BUILDFLAG(IS_APPLE)
198   // When opening journal files, propagate backup exclusion from db.
199   static int kJournalFlags =
200       SQLITE_OPEN_MAIN_JOURNAL | SQLITE_OPEN_TEMP_JOURNAL |
201       SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_MASTER_JOURNAL;
202   if (file_name && (desired_flags & kJournalFlags)) {
203     // https://www.sqlite.org/c3ref/vfs.html indicates that the journal path
204     // will have a suffix separated by "-" from the main database file name.
205     base::StringPiece file_name_string_piece(file_name);
206     size_t dash_index = file_name_string_piece.rfind('-');
207     if (dash_index != base::StringPiece::npos) {
208       base::StringPiece db_name(file_name, dash_index);
209       if (base::apple::GetBackupExclusion(base::FilePath(db_name))) {
210         base::apple::SetBackupExclusion(base::FilePath(file_name_string_piece));
211       }
212     }
213   }
214 #endif
215
216   // |iVersion| determines what methods SQLite may call on the instance.
217   // Having the methods which can't be proxied return an error may cause SQLite
218   // to operate differently than if it didn't call those methods at all. To be
219   // on the safe side, the wrapper sqlite3_io_methods version perfectly matches
220   // the version of the wrapped files.
221   //
222   // At a first glance, it might be tempting to simplify the code by
223   // restricting wrapping support to VFS version 3. However, this might fail on
224   // Mac.
225   //
226   // On Mac, SQLite built with SQLITE_ENABLE_LOCKING_STYLE ends up using a VFS
227   // that dynamically dispatches between a few variants of sqlite3_io_methods,
228   // based on whether the opened database is on a local or on a remote (AFS,
229   // NFS) filesystem. Some variants return a VFS version 1 structure.
230   VfsFile* file = AsVfsFile(wrapper_file);
231
232   // Call constructor explicitly since the memory is already allocated.
233   new (file) VfsFile();
234
235   file->wrapped_file = wrapped_file;
236
237 #if BUILDFLAG(IS_FUCHSIA)
238   file->file_name = file_name;
239 #endif
240
241   if (wrapped_file->pMethods->iVersion == 1) {
242     static const sqlite3_io_methods io_methods = {
243         1,
244         Close,
245         Read,
246         Write,
247         Truncate,
248         Sync,
249         FileSize,
250         Lock,
251         Unlock,
252         CheckReservedLock,
253         FileControl,
254         SectorSize,
255         DeviceCharacteristics,
256     };
257     file->methods = &io_methods;
258   } else if (wrapped_file->pMethods->iVersion == 2) {
259     static const sqlite3_io_methods io_methods = {
260         2,
261         Close,
262         Read,
263         Write,
264         Truncate,
265         Sync,
266         FileSize,
267         Lock,
268         Unlock,
269         CheckReservedLock,
270         FileControl,
271         SectorSize,
272         DeviceCharacteristics,
273         // Methods above are valid for version 1.
274         ShmMap,
275         ShmLock,
276         ShmBarrier,
277         ShmUnmap,
278     };
279     file->methods = &io_methods;
280   } else {
281     static const sqlite3_io_methods io_methods = {
282         3,
283         Close,
284         Read,
285         Write,
286         Truncate,
287         Sync,
288         FileSize,
289         Lock,
290         Unlock,
291         CheckReservedLock,
292         FileControl,
293         SectorSize,
294         DeviceCharacteristics,
295         // Methods above are valid for version 1.
296         ShmMap,
297         ShmLock,
298         ShmBarrier,
299         ShmUnmap,
300         // Methods above are valid for version 2.
301         Fetch,
302         Unfetch,
303     };
304     file->methods = &io_methods;
305   }
306   return SQLITE_OK;
307 }
308
309 int Delete(sqlite3_vfs* vfs, const char* file_name, int sync_dir) {
310   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
311   return wrapped_vfs->xDelete(wrapped_vfs, file_name, sync_dir);
312 }
313
314 int Access(sqlite3_vfs* vfs, const char* file_name, int flag, int* res) {
315   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
316   return wrapped_vfs->xAccess(wrapped_vfs, file_name, flag, res);
317 }
318
319 int FullPathname(sqlite3_vfs* vfs, const char* relative_path,
320                  int buf_size, char* absolute_path) {
321   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
322   return wrapped_vfs->xFullPathname(
323       wrapped_vfs, relative_path, buf_size, absolute_path);
324 }
325
326 int Randomness(sqlite3_vfs* vfs, int buf_size, char* buffer) {
327   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
328   return wrapped_vfs->xRandomness(wrapped_vfs, buf_size, buffer);
329 }
330
331 int Sleep(sqlite3_vfs* vfs, int microseconds) {
332   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
333   return wrapped_vfs->xSleep(wrapped_vfs, microseconds);
334 }
335
336 int GetLastError(sqlite3_vfs* vfs, int e, char* s) {
337   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
338   return wrapped_vfs->xGetLastError(wrapped_vfs, e, s);
339 }
340
341 int CurrentTimeInt64(sqlite3_vfs* vfs, sqlite3_int64* now) {
342   sqlite3_vfs* wrapped_vfs = GetWrappedVfs(vfs);
343   return wrapped_vfs->xCurrentTimeInt64(wrapped_vfs, now);
344 }
345
346 }  // namespace
347
348 sqlite3_vfs* VFSWrapper() {
349   static constexpr char kVFSName[] = "VFSWrapper";
350
351   // Return existing version if already registered.
352   {
353     sqlite3_vfs* vfs = sqlite3_vfs_find(kVFSName);
354     if (vfs)
355       return vfs;
356   }
357
358   // Get the default VFS on all platforms except Fuchsia.
359   static constexpr const char* kBaseVfsName =
360 #if BUILDFLAG(IS_FUCHSIA)
361       "unix-none";
362 #else
363       nullptr;
364 #endif
365   sqlite3_vfs* wrapped_vfs = sqlite3_vfs_find(kBaseVfsName);
366
367   // Give up if there is no VFS implementation for the current platform.
368   if (!wrapped_vfs) {
369     NOTREACHED();
370     return nullptr;
371   }
372
373   std::unique_ptr<sqlite3_vfs, std::function<void(sqlite3_vfs*)>> wrapper_vfs(
374       static_cast<sqlite3_vfs*>(sqlite3_malloc(sizeof(sqlite3_vfs))),
375       [](sqlite3_vfs* v) {
376         sqlite3_free(v);
377       });
378   memset(wrapper_vfs.get(), '\0', sizeof(sqlite3_vfs));
379
380   // VFS implementations should always work with a SQLite that only knows about
381   // earlier versions.
382   constexpr int kSqliteVfsApiVersion = 3;
383   wrapper_vfs->iVersion = kSqliteVfsApiVersion;
384
385   // All the SQLite VFS implementations used by Chrome should support the
386   // version proxied here.
387   DCHECK_GE(wrapped_vfs->iVersion, kSqliteVfsApiVersion);
388
389   // Caller of xOpen() allocates this much space.
390   wrapper_vfs->szOsFile = sizeof(VfsFile);
391
392   wrapper_vfs->mxPathname = wrapped_vfs->mxPathname;
393   wrapper_vfs->pNext = nullptr;  // Field used by SQLite.
394   wrapper_vfs->zName = kVFSName;
395
396   // Keep a reference to the wrapped vfs for use in methods.
397   wrapper_vfs->pAppData = wrapped_vfs;
398
399   // VFS methods.
400   wrapper_vfs->xOpen = &Open;
401   wrapper_vfs->xDelete = &Delete;
402   wrapper_vfs->xAccess = &Access;
403   wrapper_vfs->xFullPathname = &FullPathname;
404
405   // SQLite's dynamic extension loading is disabled in Chrome. Not proxying
406   // these methods lets us ship less logic and provides a tiny bit of extra
407   // security, as we know for sure that SQLite will not dynamically load code.
408   wrapper_vfs->xDlOpen = nullptr;
409   wrapper_vfs->xDlError = nullptr;
410   wrapper_vfs->xDlSym = nullptr;
411   wrapper_vfs->xDlClose = nullptr;
412
413   wrapper_vfs->xRandomness = &Randomness;
414   wrapper_vfs->xSleep = &Sleep;
415
416   // |xCurrentTime| is null when SQLite is built with SQLITE_OMIT_DEPRECATED, so
417   // it does not need to be proxied.
418   wrapper_vfs->xCurrentTime = nullptr;
419
420   wrapper_vfs->xGetLastError = &GetLastError;
421
422   // The methods above are in version 1 of SQLite's VFS API.
423
424   DCHECK(wrapped_vfs->xCurrentTimeInt64 != nullptr);
425   wrapper_vfs->xCurrentTimeInt64 = &CurrentTimeInt64;
426
427   // The methods above are in version 2 of SQLite's VFS API.
428
429   // The VFS system call interception API is intended for very low-level SQLite
430   // testing and tweaks. Proxying these methods is not necessary because Chrome
431   // does not do very low-level SQLite testing, and the VFS wrapper supports all
432   // the needed tweaks.
433   wrapper_vfs->xSetSystemCall = nullptr;
434   wrapper_vfs->xGetSystemCall = nullptr;
435   wrapper_vfs->xNextSystemCall = nullptr;
436
437   // The methods above are in version 3 of sqlite_vfs.
438
439   if (SQLITE_OK == sqlite3_vfs_register(wrapper_vfs.get(), 0)) {
440     ANNOTATE_LEAKING_OBJECT_PTR(wrapper_vfs.get());
441     wrapper_vfs.release();
442   }
443
444   return sqlite3_vfs_find(kVFSName);
445 }
446
447 }  // namespace sql