Files
palemoon27/xpcom/base/nsDumpUtils.cpp
T
roytam1 86a3aa0b54 import changes from `dev' branch of rmottola/Arctic-Fox:
- missing part of  Bug 1165772: P1. (7311039be4)
- missing gstreamer stuff (54a80d69b2)
- Bug 1214208: Do not use MP3Decoder on B2G. r=alfredo (0a19e7946e)
- Bug 1194014 - Remove redundant includes. r=jya (ccc3753113)
- Bug 1039639 - Add support for Flac on Firefox OS. r=cajbir (7d76197e07)
- Bug 875573 - Add video/x-m4v mime type. r=kentuckyfriedtakahe (6ec8af93e6)
- cleanup (6fb3d5dd26)
- Bug 1180621 - [FxOS] Enable VP9 codec for the Android version after KK. r=sotaro (58f7c2b657)
- Bug 1187247: [MSE] P2. Enable WebM in MediaSource. r=jya (2df0ee1f7a)
- Bug 1187247: [MSE] P1. Continue parsing MediaSegment if buffer starts with SimpleBlock/Block. r=kinetik (574475ed6f)
- Bug 1217170: P1. Rename functions to explicitly reflect what they are doing. r=kentuckyfriedtakahe (70c81a8179)
- Bug 1070216 - Split DOMMediaStream::InitStreamCommon into three. r=roc (1bda71cc88)
- Bug 1215582 - Rename Blacklist to Block list in GStreamerFormatReader. r=gerald (4f08077f5e)
- Bug 1170958 - Destroy track-locked MediaInputPorts when the track ends. r=roc (ff3922a2d6)
- Bug 1070216 - constify DOMMediaStream::Get[Audio/Video]Tracks(). r=roc (ba09f6f191)
- Bug 1070216 - Guard against adding a track owned by one MSG to a stream owned by another. r=padenot (a80deb8b30)
- Bug 1070216 - Implement MediaStream constructors. r=smaug,jib,padenot (3403ef2599)
- Bug 1070216 - Guard against a null MediaInputPort in DOMMediaStream::FindPlaybackDOMTrack(). r=roc (453a9ffbc1)
- Bug 1212783 - Expose TrackPort in DOMMediaStream.h r=roc (fb61c79ae7)
- Bug 1219711 - Ensure MediaStreamTrack.enabled propagates across peer connections. r=jesup (d9d1e54dae)
- Bug 1129051 - Fix double free in Camera Control Listener. Fix webrtc memory leak. r=aosmond (3e9b3bccfd)
- Bug 1152260 - Generate focused event for drivers that do not notify us when using continuous auto focus. r=mikeh (6c7bd42fdc)
- Bug 1175656 - Implement generation of recording posters in Gecko. r=dhylands,bz (51b2c66dc7)
- Bug 1187364 - Part 1. Add ability for camera to pause/resume recording. r=dhylands,bz (c54c735e37)
- Bug 1187364 - Part 2. Ensure that recording is resumed with a key frame. r=mchiang (c1c6048982)
- Bug 1187364 - Part 3. Fix missing end comment in WebIDL. r=me,bz (7faf106cc1)
- Bug 1212783 - Add a MediaStreamTrack to DOMCameraControl. r=aosmond (91e11efd3a)
- Bug 1124338 - Fix possible camera cached parameters invalidation from underlying driver modification. r=aosmond (dea67dc155)
- Bug 1196330 - Do not restart preview if configuration is unchanged. r=dhylands (097644f5d9)
- Bug 1215372 - Filter empty camera face detected events at gonk layer. r=dhylands (733efe50eb)
- Bug 1179726 - Prefer lower resolutions than 4kuhd as the default video recording profile. r=dhylands (27c71273dc)
- Bug 1222122 - Add picture size to verified parameters when reconfiguring the camera. r=dhylands (8c1fac6a4a)
- Bug 1141267 - register CameraThread with profiler, r=aosmond (299592a024)
- Bug 1008483 - removes the RW lock in CameraControlImpl and replaces it with a standard mutex. r=aosmond (45936cb90d)
- Bug 1008483 - Part 2. Readd missing nsPrintfCString.h include which has broken some local builds. r=me (9dd84b0f19)
- Bug 1191731 - Update poster API to allow application control over when poster is saved. r=bz, r=dhylands (73f9e7e0f4)
- Bug 1155648 - Fix documentation for DOMMediaStream::OnTracksAvailable. r=jesup (702828c304)
- Bug 1217170: [MSE] P2. Enable WebM/MSE on systems with no MP4/H264 support. r=kentuckyfriedtakahe (0b814b0708)
- Bug 1213177: Enable WebM on machines where H264 HW decoding is disabled. r=kentuckyfriedtakahe (e64da2ea24)
- add back some sps telemetry (52c2c64f5b)
- missing bit of Bug 1195073: [MSE/webm] P1 (9c45e82c3d)
- Bug 1150305 - sourcebuffer.buffered returns the same object if not changed. r=roc, r=bz, r=jya (6005d56c0c)
- Bug 1215447 - move flag setting from SeekStarted() to Seek(). r=roc. (a646b744c1)
- Bug 1119936 - Audio from FM Radio or Music app ceases to play when switching between front/back camera. r=roc (1a60aa7d69)
- Bug 1186806 - Part 1: Replace nsBaseHashtable::EnumerateRead() with iterators in HTMLFormControlsCollection. r=khuey (ccb8cb180a)
- Bug 1186806 - Part 2: Use NS_IMPL_CYCLE_COLLECTION_TRAVERSE instead of manual traversal in HTMLFormElement. r=khuey (57e6eabf1b)
- Bug 1186806 - Part 3: Replace nsBaseHashtable::EnumerateRead() with iterators in HTMLMediaElement. r=khuey (243ef6e83b)
- Bug 1186806 - Part 4: Replace nsBaseHashtable::EnumerateRead() with iterators in HTMLPropertiesCollection. r=khuey (499bdef85f)
- Bug 1163958 - Reduce the allocation in MediaStreamGraph - patch 3 CLOSED TREE (a557661df1)
- Bug 1219330 - Prevent the creation of TextureClient after shutdown. r=mattwoodrow (a6c047d54f)
- Bug 1205559: Make TextureChild/TextureClient thread-safe. r=nical (307c089631)
- missing bit of 1219330 (0e351ea419)
- nsRefPtr -> RefPtr (07ba248e69)
- Bug 1215023. Part 1 - make MediaDecoder::mOwner a const member. We will check mShuttingDown before calling functions of mOwner. r=kinetik. (da7f201815)
- Bug 1215023. Part 2 - remove null check of mOwner. We check mShuttingDown to know whether it is valid to call functions of mOwner. r=kinetik. (8d28a04bbe)
- Bug 1220558. Part 2 - remove unused members. r=jya. (d3a9ed8c68)
- Bug 1223599 - Remove the throttling argument from AbstractMediaDecoder::NotifyDataArrived(). r=jya. (320323ff1d)
- Bug 1194606 - Make MediaDecoderStateMachine capable of requesting different kind (decoded/raw) of media data. r=jya (1e2b6a5c44)
- Bug 1197075: P3. Decode frames ahead of MDSM requesting them. r=edwin This makes the media.*-decode-ahead pref performs more according to its name. We decode audio and video in advance so a MediaDataPromise can be resolved almost instantly. Default is 2. (b3f56447c4)
- Bug 1189964 - Fix bustage. r=bustage CLOSED TREE (afaa49b4b5)
- Bug 1212149 - e10s support for opening notification settings. r=wchen (f0e7778fb6)
- Bug 1215644 - Use child process volume service cache for available and storage status requests. r=dhylands (dfd49f2ef3)
- bug 1215552 - nsHttpConnectionMgr::PostEvent shouldnt manually ref count r=hurley (5e2f1886e6)
- Bug 1219392 - Capitalize mozilla::unused to avoid conflicts. r=froydnj (0c8bb7f15a)
- bug 1217834 - buzzfeed packet loss r=dragana (e9a60b605f)
- Bug 1168033 - Add a comment to nsHttpConnectionMgr.cpp explaining the assignment of attemptedOptimisticPipeline. r=mcmanus (2451996350)
- bug 1189645 - remove spdy telem r=hurley (cda90abbdb)
- Bug 1148268 - fixed misspelling attribute mActorDestoryed. r=dhyland. (3615d68765)
- Bug 1216031 - Make MediaDecoder::mVideoFrameContainer const. r=kinetik. (a3feb9d6bc)
- missing bits of  Bug 1165515 - Part 13-2 (009e32281f)
- Bug 1131473 - crash in -[NativeMenuItemTarget menuItemHit:]. r=spohl (ea2da6441c)
- Bug 1216416 - Fix -Wimplicit-fallthrough warnings in widget/cocoa. r=spohl (faaa390b20)
- Bug 1181977 - Firefox app menu contains only "Quit" in certain edgecases. r=spohl (0b9d912961)
2022-12-06 13:48:22 +08:00

516 lines
14 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsDumpUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "prenv.h"
#include <errno.h>
#include "mozilla/Services.h"
#include "nsIObserverService.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/unused.h"
#ifdef XP_UNIX // {
#include "mozilla/Preferences.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace mozilla;
/*
* The following code supports triggering a registered callback upon
* receiving a specific signal.
*
* Take about:memory for example, we register
* 1. doGCCCDump for doMemoryReport
* 2. doMemoryReport for sDumpAboutMemorySignum(SIGRTMIN)
* and sDumpAboutMemoryAfterMMUSignum(SIGRTMIN+1).
*
* When we receive one of these signals, we write the signal number to a pipe.
* The IO thread then notices that the pipe has been written to, and kicks off
* the appropriate task on the main thread.
*
* This scheme is similar to using signalfd(), except it's portable and it
* doesn't require the use of sigprocmask, which is problematic because it
* masks signals received by child processes.
*
* In theory, we could use Chromium's MessageLoopForIO::CatchSignal() for this.
* But that uses libevent, which does not handle the realtime signals (bug
* 794074).
*/
// This is the write-end of a pipe that we use to notice when a
// specific signal occurs.
static Atomic<int> sDumpPipeWriteFd(-1);
const char* const FifoWatcher::kPrefName =
"memory_info_dumper.watch_fifo.enabled";
static void
DumpSignalHandler(int aSignum)
{
// This is a signal handler, so everything in here needs to be
// async-signal-safe. Be careful!
if (sDumpPipeWriteFd != -1) {
uint8_t signum = static_cast<int>(aSignum);
Unused << write(sDumpPipeWriteFd, &signum, sizeof(signum));
}
}
NS_IMPL_ISUPPORTS(FdWatcher, nsIObserver);
void
FdWatcher::Init()
{
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIObserverService> os = services::GetObserverService();
os->AddObserver(this, "xpcom-shutdown", /* ownsWeak = */ false);
XRE_GetIOMessageLoop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &FdWatcher::StartWatching));
}
// Implementations may call this function multiple times if they ensure that
// it's safe to call OpenFd() multiple times and they call StopWatching()
// first.
void
FdWatcher::StartWatching()
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
MOZ_ASSERT(mFd == -1);
mFd = OpenFd();
if (mFd == -1) {
LOG("FdWatcher: OpenFd failed.");
return;
}
MessageLoopForIO::current()->WatchFileDescriptor(
mFd, /* persistent = */ true,
MessageLoopForIO::WATCH_READ,
&mReadWatcher, this);
}
// Since implementations can call StartWatching() multiple times, they can of
// course call StopWatching() multiple times.
void
FdWatcher::StopWatching()
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
mReadWatcher.StopWatchingFileDescriptor();
if (mFd != -1) {
close(mFd);
mFd = -1;
}
}
StaticRefPtr<SignalPipeWatcher> SignalPipeWatcher::sSingleton;
/* static */ SignalPipeWatcher*
SignalPipeWatcher::GetSingleton()
{
if (!sSingleton) {
sSingleton = new SignalPipeWatcher();
sSingleton->Init();
ClearOnShutdown(&sSingleton);
}
return sSingleton;
}
void
SignalPipeWatcher::RegisterCallback(uint8_t aSignal,
PipeCallback aCallback)
{
MutexAutoLock lock(mSignalInfoLock);
for (SignalInfoArray::index_type i = 0; i < mSignalInfo.Length(); ++i) {
if (mSignalInfo[i].mSignal == aSignal) {
LOG("Register Signal(%d) callback failed! (DUPLICATE)", aSignal);
return;
}
}
SignalInfo signalInfo = { aSignal, aCallback };
mSignalInfo.AppendElement(signalInfo);
RegisterSignalHandler(signalInfo.mSignal);
}
void
SignalPipeWatcher::RegisterSignalHandler(uint8_t aSignal)
{
struct sigaction action;
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_handler = DumpSignalHandler;
if (aSignal) {
if (sigaction(aSignal, &action, nullptr)) {
LOG("SignalPipeWatcher failed to register sig %d.", aSignal);
}
} else {
MutexAutoLock lock(mSignalInfoLock);
for (SignalInfoArray::index_type i = 0; i < mSignalInfo.Length(); i++) {
if (sigaction(mSignalInfo[i].mSignal, &action, nullptr)) {
LOG("SignalPipeWatcher failed to register signal(%d) "
"dump signal handler.", mSignalInfo[i].mSignal);
}
}
}
}
SignalPipeWatcher::~SignalPipeWatcher()
{
if (sDumpPipeWriteFd != -1) {
StopWatching();
}
}
int
SignalPipeWatcher::OpenFd()
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
// Create a pipe. When we receive a signal in our signal handler, we'll
// write the signum to the write-end of this pipe.
int pipeFds[2];
if (pipe(pipeFds)) {
LOG("SignalPipeWatcher failed to create pipe.");
return -1;
}
// Close this pipe on calls to exec().
fcntl(pipeFds[0], F_SETFD, FD_CLOEXEC);
fcntl(pipeFds[1], F_SETFD, FD_CLOEXEC);
int readFd = pipeFds[0];
sDumpPipeWriteFd = pipeFds[1];
RegisterSignalHandler();
return readFd;
}
void
SignalPipeWatcher::StopWatching()
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
// Close sDumpPipeWriteFd /after/ setting the fd to -1.
// Otherwise we have the (admittedly far-fetched) race where we
//
// 1) close sDumpPipeWriteFd
// 2) open a new fd with the same number as sDumpPipeWriteFd
// had.
// 3) receive a signal, then write to the fd.
int pipeWriteFd = sDumpPipeWriteFd.exchange(-1);
close(pipeWriteFd);
FdWatcher::StopWatching();
}
void
SignalPipeWatcher::OnFileCanReadWithoutBlocking(int aFd)
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
uint8_t signum;
ssize_t numReceived = read(aFd, &signum, sizeof(signum));
if (numReceived != sizeof(signum)) {
LOG("Error reading from buffer in "
"SignalPipeWatcher::OnFileCanReadWithoutBlocking.");
return;
}
{
MutexAutoLock lock(mSignalInfoLock);
for (SignalInfoArray::index_type i = 0; i < mSignalInfo.Length(); i++) {
if (signum == mSignalInfo[i].mSignal) {
mSignalInfo[i].mCallback(signum);
return;
}
}
}
LOG("SignalPipeWatcher got unexpected signum.");
}
StaticRefPtr<FifoWatcher> FifoWatcher::sSingleton;
/* static */ FifoWatcher*
FifoWatcher::GetSingleton()
{
if (!sSingleton) {
nsAutoCString dirPath;
Preferences::GetCString(
"memory_info_dumper.watch_fifo.directory", &dirPath);
sSingleton = new FifoWatcher(dirPath);
sSingleton->Init();
ClearOnShutdown(&sSingleton);
}
return sSingleton;
}
/* static */ bool
FifoWatcher::MaybeCreate()
{
MOZ_ASSERT(NS_IsMainThread());
if (!XRE_IsParentProcess()) {
// We want this to be main-process only, since two processes can't listen
// to the same fifo.
return false;
}
if (!Preferences::GetBool(kPrefName, false)) {
LOG("Fifo watcher disabled via pref.");
return false;
}
// The FifoWatcher is held alive by the observer service.
if (!sSingleton) {
GetSingleton();
}
return true;
}
void
FifoWatcher::RegisterCallback(const nsCString& aCommand, FifoCallback aCallback)
{
MutexAutoLock lock(mFifoInfoLock);
for (FifoInfoArray::index_type i = 0; i < mFifoInfo.Length(); ++i) {
if (mFifoInfo[i].mCommand.Equals(aCommand)) {
LOG("Register command(%s) callback failed! (DUPLICATE)", aCommand.get());
return;
}
}
FifoInfo aFifoInfo = { aCommand, aCallback };
mFifoInfo.AppendElement(aFifoInfo);
}
FifoWatcher::~FifoWatcher()
{
}
int
FifoWatcher::OpenFd()
{
// If the memory_info_dumper.directory pref is specified, put the fifo
// there. Otherwise, put it into the system's tmp directory.
nsCOMPtr<nsIFile> file;
nsresult rv;
if (mDirPath.Length() > 0) {
rv = XRE_GetFileFromPath(mDirPath.get(), getter_AddRefs(file));
if (NS_FAILED(rv)) {
LOG("FifoWatcher failed to open file \"%s\"", mDirPath.get());
return -1;
}
} else {
rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(file));
if (NS_WARN_IF(NS_FAILED(rv))) {
return -1;
}
}
rv = file->AppendNative(NS_LITERAL_CSTRING("debug_info_trigger"));
if (NS_WARN_IF(NS_FAILED(rv))) {
return -1;
}
nsAutoCString path;
rv = file->GetNativePath(path);
if (NS_WARN_IF(NS_FAILED(rv))) {
return -1;
}
// unlink might fail because the file doesn't exist, or for other reasons.
// But we don't care it fails; any problems will be detected later, when we
// try to mkfifo or open the file.
if (unlink(path.get())) {
LOG("FifoWatcher::OpenFifo unlink failed; errno=%d. "
"Continuing despite error.", errno);
}
if (mkfifo(path.get(), 0766)) {
LOG("FifoWatcher::OpenFifo mkfifo failed; errno=%d", errno);
return -1;
}
#ifdef ANDROID
// Android runs with a umask, so we need to chmod our fifo to make it
// world-writable.
chmod(path.get(), 0666);
#endif
int fd;
do {
// The fifo will block until someone else has written to it. In
// particular, open() will block until someone else has opened it for
// writing! We want open() to succeed and read() to block, so we open
// with NONBLOCK and then fcntl that away.
fd = open(path.get(), O_RDONLY | O_NONBLOCK);
} while (fd == -1 && errno == EINTR);
if (fd == -1) {
LOG("FifoWatcher::OpenFifo open failed; errno=%d", errno);
return -1;
}
// Make fd blocking now that we've opened it.
if (fcntl(fd, F_SETFL, 0)) {
close(fd);
return -1;
}
return fd;
}
void
FifoWatcher::OnFileCanReadWithoutBlocking(int aFd)
{
MOZ_ASSERT(XRE_GetIOMessageLoop() == MessageLoopForIO::current());
char buf[1024];
int nread;
do {
// sizeof(buf) - 1 to leave space for the null-terminator.
nread = read(aFd, buf, sizeof(buf));
} while (nread == -1 && errno == EINTR);
if (nread == -1) {
// We want to avoid getting into a situation where
// OnFileCanReadWithoutBlocking is called in an infinite loop, so when
// something goes wrong, stop watching the fifo altogether.
LOG("FifoWatcher hit an error (%d) and is quitting.", errno);
StopWatching();
return;
}
if (nread == 0) {
// If we get EOF, that means that the other side closed the fifo. We need
// to close and re-open the fifo; if we don't,
// OnFileCanWriteWithoutBlocking will be called in an infinite loop.
LOG("FifoWatcher closing and re-opening fifo.");
StopWatching();
StartWatching();
return;
}
nsAutoCString inputStr;
inputStr.Append(buf, nread);
// Trimming whitespace is important because if you do
// |echo "foo" >> debug_info_trigger|,
// it'll actually write "foo\n" to the fifo.
inputStr.Trim("\b\t\r\n");
{
MutexAutoLock lock(mFifoInfoLock);
for (FifoInfoArray::index_type i = 0; i < mFifoInfo.Length(); i++) {
const nsCString commandStr = mFifoInfo[i].mCommand;
if (inputStr == commandStr.get()) {
mFifoInfo[i].mCallback(inputStr);
return;
}
}
}
LOG("Got unexpected value from fifo; ignoring it.");
}
#endif // XP_UNIX }
// In Android case, this function will open a file named aFilename under
// /data/local/tmp/"aFoldername".
// Otherwise, it will open a file named aFilename under "NS_OS_TEMP_DIR".
/* static */ nsresult
nsDumpUtils::OpenTempFile(const nsACString& aFilename, nsIFile** aFile,
const nsACString& aFoldername, Mode aMode)
{
#ifdef ANDROID
// For Android, first try the downloads directory which is world-readable
// rather than the temp directory which is not.
if (!*aFile) {
char* env = PR_GetEnv("DOWNLOADS_DIRECTORY");
if (env) {
NS_NewNativeLocalFile(nsCString(env), /* followLinks = */ true, aFile);
}
}
#endif
nsresult rv;
if (!*aFile) {
rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, aFile);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
#ifdef ANDROID
// /data/local/tmp is a true tmp directory; anyone can create a file there,
// but only the user which created the file can remove it. We want non-root
// users to be able to remove these files, so we write them into a
// subdirectory of the temp directory and chmod 777 that directory.
if (aFoldername != EmptyCString()) {
rv = (*aFile)->AppendNative(aFoldername);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// It's OK if this fails; that probably just means that the directory already
// exists.
(*aFile)->Create(nsIFile::DIRECTORY_TYPE, 0777);
nsAutoCString dirPath;
rv = (*aFile)->GetNativePath(dirPath);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
while (chmod(dirPath.get(), 0777) == -1 && errno == EINTR) {
}
}
#endif
nsCOMPtr<nsIFile> file(*aFile);
rv = file->AppendNative(aFilename);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aMode == CREATE_UNIQUE) {
rv = file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0666);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
} else {
file->Create(nsIFile::NORMAL_FILE_TYPE, 0666);
}
#ifdef ANDROID
// Make this file world-read/writable; the permissions passed to the
// CreateUnique call above are not sufficient on Android, which runs with a
// umask.
nsAutoCString path;
rv = file->GetNativePath(path);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
while (chmod(path.get(), 0666) == -1 && errno == EINTR) {
}
#endif
return NS_OK;
}