@@ -20,11 +20,7 @@ import (
20
20
// [EXCLUSIVE locking mode]: https://sqlite.org/pragma.html#pragma_locking_mode
21
21
const SupportsSharedMemory = true
22
22
23
- const (
24
- _SHM_NLOCK = 8
25
- _SHM_BASE = 120
26
- _SHM_DMS = _SHM_BASE + _SHM_NLOCK
27
- )
23
+ const _SHM_NLOCK = 8
28
24
29
25
func (f * vfsFile ) SharedMemory () SharedMemory { return f .shm }
30
26
@@ -100,22 +96,19 @@ func (s *vfsShm) Close() error {
100
96
return err
101
97
}
102
98
103
- func (s * vfsShm ) shmOpen () error {
99
+ func (s * vfsShm ) shmOpen () ( err error ) {
104
100
if s .vfsShmFile != nil {
105
101
return nil
106
102
}
107
103
108
- var flag int
109
- if s .readOnly {
110
- flag = unix .O_RDONLY
111
- } else {
112
- flag = unix .O_RDWR
113
- }
104
+ // Open file read-write, as it will be shared.
114
105
f , err := os .OpenFile (s .path ,
115
- flag | unix .O_CREAT | unix .O_NOFOLLOW , 0666 )
106
+ unix . O_RDWR | unix .O_CREAT | unix .O_NOFOLLOW , 0666 )
116
107
if err != nil {
117
108
return _CANTOPEN
118
109
}
110
+ // Close if file if it's not nil.
111
+ defer func () { f .Close () }()
119
112
120
113
fi , err := f .Stat ()
121
114
if err != nil {
@@ -125,19 +118,34 @@ func (s *vfsShm) shmOpen() error {
125
118
vfsShmFilesMtx .Lock ()
126
119
defer vfsShmFilesMtx .Unlock ()
127
120
121
+ // Find a shared file, increase the reference count.
128
122
for _ , g := range vfsShmFiles {
129
123
if g != nil && os .SameFile (fi , g .info ) {
130
- f .Close ()
131
124
g .refs ++
132
125
s .vfsShmFile = g
133
126
return nil
134
127
}
135
128
}
129
+
130
+ // Lock and truncate the file, if not readonly.
131
+ if s .readOnly {
132
+ err = _READONLY_CANTINIT
133
+ } else {
134
+ if rc := osWriteLock (f , 0 , 0 , 0 ); rc != _OK {
135
+ return rc
136
+ }
137
+ if err := f .Truncate (0 ); err != nil {
138
+ return _IOERR_SHMOPEN
139
+ }
140
+ }
141
+
142
+ // Add the new shared file.
136
143
s .vfsShmFile = & vfsShmFile {
137
144
File : f ,
138
145
info : fi ,
139
146
refs : 1 ,
140
147
}
148
+ f = nil
141
149
add := true
142
150
for i , g := range vfsShmFiles {
143
151
if g == nil {
@@ -148,17 +156,7 @@ func (s *vfsShm) shmOpen() error {
148
156
if add {
149
157
vfsShmFiles = append (vfsShmFiles , s .vfsShmFile )
150
158
}
151
-
152
- if s .readOnly {
153
- return _READONLY_CANTINIT
154
- }
155
- if rc := osWriteLock (f , _SHM_DMS , 1 , 0 ); rc != _OK {
156
- return rc
157
- }
158
- if err := f .Truncate (0 ); err != nil {
159
- return _IOERR_SHMOPEN
160
- }
161
- return nil
159
+ return err
162
160
}
163
161
164
162
func (s * vfsShm ) shmMap (ctx context.Context , mod api.Module , id , size int32 , extend bool ) (uint32 , error ) {
0 commit comments