1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsDumpUtils.h"
8 #include "nsDirectoryServiceDefs.h"
9 #include "nsDirectoryServiceUtils.h"
12 #include "mozilla/Services.h"
13 #include "nsIObserverService.h"
14 #include "mozilla/ClearOnShutdown.h"
17 #include "mozilla/Preferences.h"
20 #include <sys/types.h>
23 using namespace mozilla
;
26 * The following code supports triggering a registered callback upon
27 * receiving a specific signal.
29 * Take about:memory for example, we register
30 * 1. doGCCCDump for doMemoryReport
31 * 2. doMemoryReport for sDumpAboutMemorySignum(SIGRTMIN)
32 * and sDumpAboutMemoryAfterMMUSignum(SIGRTMIN+1).
34 * When we receive one of these signals, we write the signal number to a pipe.
35 * The IO thread then notices that the pipe has been written to, and kicks off
36 * the appropriate task on the main thread.
38 * This scheme is similar to using signalfd(), except it's portable and it
39 * doesn't require the use of sigprocmask, which is problematic because it
40 * masks signals received by child processes.
42 * In theory, we could use Chromium's MessageLoopForIO::CatchSignal() for this.
43 * But that uses libevent, which does not handle the realtime signals (bug
47 // This is the write-end of a pipe that we use to notice when a
48 // specific signal occurs.
49 static Atomic
<int> sDumpPipeWriteFd(-1);
51 const char* const FifoWatcher::kPrefName
=
52 "memory_info_dumper.watch_fifo.enabled";
55 DumpSignalHandler(int aSignum
)
57 // This is a signal handler, so everything in here needs to be
58 // async-signal-safe. Be careful!
60 if (sDumpPipeWriteFd
!= -1) {
61 uint8_t signum
= static_cast<int>(aSignum
);
62 write(sDumpPipeWriteFd
, &signum
, sizeof(signum
));
66 NS_IMPL_ISUPPORTS(FdWatcher
, nsIObserver
);
71 MOZ_ASSERT(NS_IsMainThread());
73 nsCOMPtr
<nsIObserverService
> os
= services::GetObserverService();
74 os
->AddObserver(this, "xpcom-shutdown", /* ownsWeak = */ false);
76 XRE_GetIOMessageLoop()->PostTask(
78 NewRunnableMethod(this, &FdWatcher::StartWatching
));
81 // Implementations may call this function multiple times if they ensure that
82 // it's safe to call OpenFd() multiple times and they call StopWatching()
85 FdWatcher::StartWatching()
87 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
88 MOZ_ASSERT(mFd
== -1);
92 LOG("FdWatcher: OpenFd failed.");
96 MessageLoopForIO::current()->WatchFileDescriptor(
97 mFd
, /* persistent = */ true,
98 MessageLoopForIO::WATCH_READ
,
102 // Since implementations can call StartWatching() multiple times, they can of
103 // course call StopWatching() multiple times.
105 FdWatcher::StopWatching()
107 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
109 mReadWatcher
.StopWatchingFileDescriptor();
116 StaticRefPtr
<SignalPipeWatcher
> SignalPipeWatcher::sSingleton
;
118 /* static */ SignalPipeWatcher
*
119 SignalPipeWatcher::GetSingleton()
122 sSingleton
= new SignalPipeWatcher();
124 ClearOnShutdown(&sSingleton
);
130 SignalPipeWatcher::RegisterCallback(uint8_t aSignal
,
131 PipeCallback aCallback
)
133 MutexAutoLock
lock(mSignalInfoLock
);
135 for (SignalInfoArray::index_type i
= 0; i
< mSignalInfo
.Length(); ++i
) {
136 if (mSignalInfo
[i
].mSignal
== aSignal
) {
137 LOG("Register Signal(%d) callback failed! (DUPLICATE)", aSignal
);
141 SignalInfo signalInfo
= { aSignal
, aCallback
};
142 mSignalInfo
.AppendElement(signalInfo
);
143 RegisterSignalHandler(signalInfo
.mSignal
);
147 SignalPipeWatcher::RegisterSignalHandler(uint8_t aSignal
)
149 struct sigaction action
;
150 memset(&action
, 0, sizeof(action
));
151 sigemptyset(&action
.sa_mask
);
152 action
.sa_handler
= DumpSignalHandler
;
155 if (sigaction(aSignal
, &action
, nullptr)) {
156 LOG("SignalPipeWatcher failed to register sig %d.", aSignal
);
159 MutexAutoLock
lock(mSignalInfoLock
);
160 for (SignalInfoArray::index_type i
= 0; i
< mSignalInfo
.Length(); i
++) {
161 if (sigaction(mSignalInfo
[i
].mSignal
, &action
, nullptr)) {
162 LOG("SignalPipeWatcher failed to register signal(%d) "
163 "dump signal handler.", mSignalInfo
[i
].mSignal
);
169 SignalPipeWatcher::~SignalPipeWatcher()
171 if (sDumpPipeWriteFd
!= -1) {
177 SignalPipeWatcher::OpenFd()
179 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
181 // Create a pipe. When we receive a signal in our signal handler, we'll
182 // write the signum to the write-end of this pipe.
185 LOG("SignalPipeWatcher failed to create pipe.");
189 // Close this pipe on calls to exec().
190 fcntl(pipeFds
[0], F_SETFD
, FD_CLOEXEC
);
191 fcntl(pipeFds
[1], F_SETFD
, FD_CLOEXEC
);
193 int readFd
= pipeFds
[0];
194 sDumpPipeWriteFd
= pipeFds
[1];
196 RegisterSignalHandler();
201 SignalPipeWatcher::StopWatching()
203 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
205 // Close sDumpPipeWriteFd /after/ setting the fd to -1.
206 // Otherwise we have the (admittedly far-fetched) race where we
208 // 1) close sDumpPipeWriteFd
209 // 2) open a new fd with the same number as sDumpPipeWriteFd
211 // 3) receive a signal, then write to the fd.
212 int pipeWriteFd
= sDumpPipeWriteFd
.exchange(-1);
215 FdWatcher::StopWatching();
219 SignalPipeWatcher::OnFileCanReadWithoutBlocking(int aFd
)
221 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
224 ssize_t numReceived
= read(aFd
, &signum
, sizeof(signum
));
225 if (numReceived
!= sizeof(signum
)) {
226 LOG("Error reading from buffer in "
227 "SignalPipeWatcher::OnFileCanReadWithoutBlocking.");
232 MutexAutoLock
lock(mSignalInfoLock
);
233 for (SignalInfoArray::index_type i
= 0; i
< mSignalInfo
.Length(); i
++) {
234 if (signum
== mSignalInfo
[i
].mSignal
) {
235 mSignalInfo
[i
].mCallback(signum
);
240 LOG("SignalPipeWatcher got unexpected signum.");
243 StaticRefPtr
<FifoWatcher
> FifoWatcher::sSingleton
;
245 /* static */ FifoWatcher
*
246 FifoWatcher::GetSingleton()
249 nsAutoCString dirPath
;
250 Preferences::GetCString(
251 "memory_info_dumper.watch_fifo.directory", &dirPath
);
252 sSingleton
= new FifoWatcher(dirPath
);
254 ClearOnShutdown(&sSingleton
);
260 FifoWatcher::MaybeCreate()
262 MOZ_ASSERT(NS_IsMainThread());
264 if (XRE_GetProcessType() != GeckoProcessType_Default
) {
265 // We want this to be main-process only, since two processes can't listen
270 if (!Preferences::GetBool(kPrefName
, false)) {
271 LOG("Fifo watcher disabled via pref.");
275 // The FifoWatcher is held alive by the observer service.
283 FifoWatcher::RegisterCallback(const nsCString
& aCommand
, FifoCallback aCallback
)
285 MutexAutoLock
lock(mFifoInfoLock
);
287 for (FifoInfoArray::index_type i
= 0; i
< mFifoInfo
.Length(); ++i
) {
288 if (mFifoInfo
[i
].mCommand
.Equals(aCommand
)) {
289 LOG("Register command(%s) callback failed! (DUPLICATE)", aCommand
.get());
293 FifoInfo aFifoInfo
= { aCommand
, aCallback
};
294 mFifoInfo
.AppendElement(aFifoInfo
);
297 FifoWatcher::~FifoWatcher()
302 FifoWatcher::OpenFd()
304 // If the memory_info_dumper.directory pref is specified, put the fifo
305 // there. Otherwise, put it into the system's tmp directory.
307 nsCOMPtr
<nsIFile
> file
;
310 if (mDirPath
.Length() > 0) {
311 rv
= XRE_GetFileFromPath(mDirPath
.get(), getter_AddRefs(file
));
313 LOG("FifoWatcher failed to open file \"%s\"", mDirPath
.get());
317 rv
= NS_GetSpecialDirectory(NS_OS_TEMP_DIR
, getter_AddRefs(file
));
318 if (NS_WARN_IF(NS_FAILED(rv
))) {
323 rv
= file
->AppendNative(NS_LITERAL_CSTRING("debug_info_trigger"));
324 if (NS_WARN_IF(NS_FAILED(rv
))) {
329 rv
= file
->GetNativePath(path
);
330 if (NS_WARN_IF(NS_FAILED(rv
))) {
334 // unlink might fail because the file doesn't exist, or for other reasons.
335 // But we don't care it fails; any problems will be detected later, when we
336 // try to mkfifo or open the file.
337 if (unlink(path
.get())) {
338 LOG("FifoWatcher::OpenFifo unlink failed; errno=%d. "
339 "Continuing despite error.", errno
);
342 if (mkfifo(path
.get(), 0766)) {
343 LOG("FifoWatcher::OpenFifo mkfifo failed; errno=%d", errno
);
348 // Android runs with a umask, so we need to chmod our fifo to make it
350 chmod(path
.get(), 0666);
355 // The fifo will block until someone else has written to it. In
356 // particular, open() will block until someone else has opened it for
357 // writing! We want open() to succeed and read() to block, so we open
358 // with NONBLOCK and then fcntl that away.
359 fd
= open(path
.get(), O_RDONLY
| O_NONBLOCK
);
360 } while (fd
== -1 && errno
== EINTR
);
363 LOG("FifoWatcher::OpenFifo open failed; errno=%d", errno
);
367 // Make fd blocking now that we've opened it.
368 if (fcntl(fd
, F_SETFL
, 0)) {
377 FifoWatcher::OnFileCanReadWithoutBlocking(int aFd
)
379 MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
384 // sizeof(buf) - 1 to leave space for the null-terminator.
385 nread
= read(aFd
, buf
, sizeof(buf
));
386 } while (nread
== -1 && errno
== EINTR
);
389 // We want to avoid getting into a situation where
390 // OnFileCanReadWithoutBlocking is called in an infinite loop, so when
391 // something goes wrong, stop watching the fifo altogether.
392 LOG("FifoWatcher hit an error (%d) and is quitting.", errno
);
398 // If we get EOF, that means that the other side closed the fifo. We need
399 // to close and re-open the fifo; if we don't,
400 // OnFileCanWriteWithoutBlocking will be called in an infinite loop.
402 LOG("FifoWatcher closing and re-opening fifo.");
408 nsAutoCString inputStr
;
409 inputStr
.Append(buf
, nread
);
411 // Trimming whitespace is important because if you do
412 // |echo "foo" >> debug_info_trigger|,
413 // it'll actually write "foo\n" to the fifo.
414 inputStr
.Trim("\b\t\r\n");
417 MutexAutoLock
lock(mFifoInfoLock
);
419 for (FifoInfoArray::index_type i
= 0; i
< mFifoInfo
.Length(); i
++) {
420 const nsCString commandStr
= mFifoInfo
[i
].mCommand
;
421 if (inputStr
== commandStr
.get()) {
422 mFifoInfo
[i
].mCallback(inputStr
);
427 LOG("Got unexpected value from fifo; ignoring it.");
432 // In Android case, this function will open a file named aFilename under
433 // /data/local/tmp/"aFoldername".
434 // Otherwise, it will open a file named aFilename under "NS_OS_TEMP_DIR".
435 /* static */ nsresult
436 nsDumpUtils::OpenTempFile(const nsACString
& aFilename
, nsIFile
** aFile
,
437 const nsACString
& aFoldername
)
440 // For Android, first try the downloads directory which is world-readable
441 // rather than the temp directory which is not.
443 char* env
= PR_GetEnv("DOWNLOADS_DIRECTORY");
445 NS_NewNativeLocalFile(nsCString(env
), /* followLinks = */ true, aFile
);
451 rv
= NS_GetSpecialDirectory(NS_OS_TEMP_DIR
, aFile
);
452 if (NS_WARN_IF(NS_FAILED(rv
))) {
458 // /data/local/tmp is a true tmp directory; anyone can create a file there,
459 // but only the user which created the file can remove it. We want non-root
460 // users to be able to remove these files, so we write them into a
461 // subdirectory of the temp directory and chmod 777 that directory.
462 if (aFoldername
!= EmptyCString()) {
463 rv
= (*aFile
)->AppendNative(aFoldername
);
464 if (NS_WARN_IF(NS_FAILED(rv
))) {
468 // It's OK if this fails; that probably just means that the directory already
470 (*aFile
)->Create(nsIFile::DIRECTORY_TYPE
, 0777);
472 nsAutoCString dirPath
;
473 rv
= (*aFile
)->GetNativePath(dirPath
);
474 if (NS_WARN_IF(NS_FAILED(rv
))) {
478 while (chmod(dirPath
.get(), 0777) == -1 && errno
== EINTR
) {
483 nsCOMPtr
<nsIFile
> file(*aFile
);
485 rv
= file
->AppendNative(aFilename
);
486 if (NS_WARN_IF(NS_FAILED(rv
))) {
490 rv
= file
->CreateUnique(nsIFile::NORMAL_FILE_TYPE
, 0666);
491 if (NS_WARN_IF(NS_FAILED(rv
))) {
496 // Make this file world-read/writable; the permissions passed to the
497 // CreateUnique call above are not sufficient on Android, which runs with a
500 rv
= file
->GetNativePath(path
);
501 if (NS_WARN_IF(NS_FAILED(rv
))) {
505 while (chmod(path
.get(), 0666) == -1 && errno
== EINTR
) {