Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "lib/sysdep/dir_watch.h"
26 :
27 : #include "lib/debug.h"
28 : #include "lib/os_path.h"
29 : #include "lib/path.h"
30 : #include "lib/posix/posix_pthread.h"
31 : #include "lib/posix/posix_types.h"
32 : #include "lib/status.h"
33 : #include "ps/CLogger.h"
34 :
35 : #include <cerrno>
36 : #include <climits>
37 : #include <cstddef>
38 : #include <cstdint>
39 : #include <cstdlib>
40 : #include <map>
41 : #include <memory>
42 : #include <string>
43 : #include <sys/inotify.h>
44 : #include <sys/select.h>
45 : #include <utility>
46 : #include <vector>
47 :
48 32 : struct NotificationEvent
49 : {
50 : std::string filename;
51 : uint32_t code;
52 : int wd;
53 : };
54 :
55 : // To avoid deadlocks and slow synchronous reads, it's necessary to use a
56 : // separate thread for reading events from inotify.
57 : // So we just spawn a thread to push events into this list, then swap it out
58 : // when someone calls dir_watch_Poll.
59 : // (We assume STL memory allocation is thread-safe.)
60 : static std::vector<NotificationEvent> g_notifications;
61 : static pthread_t g_event_loop_thread;
62 :
63 : // Mutex must wrap all accesses of g_notifications
64 : // while the event loop thread is running
65 : static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
66 :
67 : // trool; -1 = init failed and all operations will be aborted silently.
68 : // this is so that each dir_* call doesn't complain if the system's
69 : // inotify is broken or unavailable.
70 : static int initialized = 0;
71 :
72 : // Inotify file descriptor
73 : static int inotifyfd;
74 :
75 : // With inotify, using a map seems to be a good alternative to FAM's userdata
76 : typedef std::map<int, PDirWatch> DirWatchMap;
77 : static DirWatchMap g_paths;
78 :
79 : struct DirWatch
80 : {
81 9 : DirWatch()
82 18 : : reqnum(-1)
83 : {
84 : }
85 :
86 9 : ~DirWatch()
87 : {
88 9 : ENSURE(initialized > 0);
89 9 : inotify_rm_watch(inotifyfd, reqnum);
90 9 : }
91 :
92 : OsPath path;
93 : int reqnum;
94 : };
95 :
96 : // for atexit
97 1 : static void inotify_deinit()
98 : {
99 1 : close(inotifyfd);
100 :
101 : #ifdef __BIONIC__
102 : #warning TODO: pthread_cancel not supported on Bionic
103 : #else
104 1 : pthread_cancel(g_event_loop_thread);
105 : #endif
106 : // NOTE: POSIX threads are (by default) only cancellable inside particular
107 : // functions (like 'select'), so this should safely terminate while it's
108 : // in select/etc (and won't e.g. cancel while it's holding the
109 : // mutex)
110 :
111 : // Wait for the thread to finish
112 1 : pthread_join(g_event_loop_thread, NULL);
113 1 : }
114 :
115 13 : static void inotify_event_loop_process_events()
116 : {
117 : // Buffer for reading the events.
118 : // Need to be careful about overflow here.
119 13 : char buffer[65535] = {0};
120 :
121 : // Event iterator
122 13 : ssize_t buffer_i = 0;
123 :
124 : // Total size of all the events
125 13 : ssize_t r;
126 :
127 : // Size & struct for the current event
128 13 : size_t event_size;
129 13 : struct inotify_event *pevent;
130 :
131 13 : r = read(inotifyfd, buffer, 65535);
132 13 : if(r <= 0)
133 0 : return;
134 :
135 26 : while(buffer_i < r)
136 : {
137 13 : NotificationEvent ne;
138 13 : pevent = (struct inotify_event *) &buffer[buffer_i];
139 :
140 13 : event_size = offsetof(struct inotify_event, name) + pevent->len;
141 13 : ne.wd = pevent->wd;
142 13 : ne.filename = pevent->name;
143 13 : ne.code = pevent->mask;
144 :
145 13 : pthread_mutex_lock(&g_mutex);
146 13 : g_notifications.push_back(ne);
147 13 : pthread_mutex_unlock(&g_mutex);
148 :
149 13 : buffer_i += event_size;
150 13 : }
151 : }
152 :
153 1 : static void* inotify_event_loop(void*)
154 : {
155 27 : while(true)
156 : {
157 14 : fd_set fdrset;
158 238 : FD_ZERO(&fdrset);
159 14 : FD_SET(inotifyfd, &fdrset);
160 14 : errno = 0;
161 : // Block with select until there's events waiting
162 14 : while(select(inotifyfd+1, &fdrset, NULL, NULL, NULL) < 0)
163 : {
164 0 : if(errno == EINTR)
165 : {
166 : // interrupted - try again
167 0 : FD_ZERO(&fdrset);
168 0 : FD_SET(inotifyfd, &fdrset);
169 : }
170 0 : else if(errno == EBADF)
171 : {
172 : // probably just lost the connection to inotify - kill the thread
173 0 : debug_printf("inotify_event_loop: Invalid file descriptor inotifyfd=%d\n", inotifyfd);
174 0 : return NULL;
175 : }
176 : else
177 : {
178 : // oops
179 0 : debug_printf("inotify_event_loop: select error errno=%d\n", errno);
180 0 : return NULL;
181 : }
182 0 : errno = 0;
183 : }
184 13 : if(FD_ISSET(inotifyfd, &fdrset))
185 13 : inotify_event_loop_process_events();
186 13 : }
187 : }
188 :
189 9 : Status dir_watch_Add(const OsPath& path, PDirWatch& dirWatch)
190 : {
191 9 : char resolved[PATH_MAX + 1];
192 :
193 : // init already failed; don't try again or complain
194 9 : if(initialized == -1)
195 : return ERR::FAIL; // NOWARN
196 :
197 9 : if(!initialized)
198 : {
199 1 : errno = 0;
200 1 : if((inotifyfd = inotify_init()) < 0)
201 : {
202 : // Check for error ?
203 0 : int err = errno;
204 0 : initialized = -1;
205 0 : LOGERROR("Error initializing inotify file descriptor; hotloading will be disabled, "
206 : "errno={}", err);
207 0 : errno = err;
208 0 : return StatusFromErrno(); // NOWARN
209 : }
210 :
211 1 : errno = 0;
212 1 : int ret = pthread_create(&g_event_loop_thread, NULL, &inotify_event_loop, NULL);
213 1 : if (ret != 0)
214 : {
215 0 : initialized = -1;
216 0 : LOGERROR("Error creating inotify event loop thread; hotloading will be disabled, err={}",
217 : ret);
218 0 : errno = ret;
219 0 : return StatusFromErrno(); // NOWARN
220 : }
221 :
222 1 : initialized = 1;
223 1 : atexit(inotify_deinit);
224 : }
225 :
226 9 : PDirWatch tmpDirWatch(new DirWatch);
227 9 : errno = 0;
228 9 : int wd = inotify_add_watch(inotifyfd, realpath(OsString(path).c_str(), resolved), IN_CREATE | IN_DELETE | IN_CLOSE_WRITE);
229 9 : if (wd < 0)
230 0 : WARN_RETURN(StatusFromErrno());
231 :
232 9 : dirWatch.swap(tmpDirWatch);
233 9 : dirWatch->path = path;
234 9 : dirWatch->reqnum = wd;
235 9 : g_paths.insert(std::make_pair(wd, dirWatch));
236 :
237 9 : return INFO::OK;
238 9 : }
239 :
240 9 : Status dir_watch_Poll(DirWatchNotifications& notifications)
241 : {
242 9 : if(initialized == -1)
243 : return ERR::FAIL; // NOWARN
244 9 : if(!initialized) // XXX Fix Atlas instead of suppressing the warning
245 : return ERR::FAIL; //WARN_RETURN(ERR::LOGIC);
246 :
247 9 : std::vector<NotificationEvent> polled_notifications;
248 :
249 9 : pthread_mutex_lock(&g_mutex);
250 9 : g_notifications.swap(polled_notifications);
251 9 : pthread_mutex_unlock(&g_mutex);
252 :
253 22 : for(size_t i = 0; i < polled_notifications.size(); ++i)
254 : {
255 13 : DirWatchNotification::EType type;
256 : // TODO: code is actually a bitmask, so this is slightly incorrect
257 13 : switch(polled_notifications[i].code)
258 : {
259 : case IN_CLOSE_WRITE:
260 : type = DirWatchNotification::Changed;
261 : break;
262 0 : case IN_CREATE:
263 0 : type = DirWatchNotification::Created;
264 0 : break;
265 0 : case IN_DELETE:
266 0 : type = DirWatchNotification::Deleted;
267 0 : break;
268 4 : default:
269 4 : continue;
270 : }
271 :
272 9 : DirWatchMap::iterator it = g_paths.find(polled_notifications[i].wd);
273 9 : if(it != g_paths.end())
274 : {
275 9 : OsPath filename = Path(OsString(it->second->path).append(polled_notifications[i].filename));
276 9 : notifications.push_back(DirWatchNotification(filename, type));
277 9 : }
278 : else
279 : {
280 0 : debug_printf("dir_watch_Poll: Notification with invalid watch descriptor wd=%d\n", polled_notifications[i].wd);
281 : }
282 : }
283 :
284 : // nothing new; try again later
285 9 : return INFO::OK;
286 9 : }
287 :
|