#include "content/public/common/profiling_utils.h"
#include <limits>
#include <memory>
#include <string>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/rand_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
namespace content {
namespace {
base::FilePath GetProfileFileDirectory() {
base::FilePath path;
#if BUILDFLAG(IS_ANDROID)
base::PathService::Get(base::DIR_TEMP, &path);
path = path.Append("pgo_profiles/");
#else
std::unique_ptr<base::Environment> env(base::Environment::Create());
std::optional<std::string> prof_template = env->GetVar("LLVM_PROFILE_FILE");
if (prof_template.has_value()) {
#if BUILDFLAG(IS_WIN)
path = base::FilePath(base::UTF8ToWide(*prof_template)).DirName();
#else
path = base::FilePath(*prof_template).DirName();
#endif
}
#endif
if (!path.empty()) {
base::CreateDirectory(path);
} else {
base::PathService::Get(base::DIR_CURRENT, &path);
}
return path;
}
}
base::File OpenProfilingFile() {
base::ScopedAllowBlockingForTesting allows_blocking;
base::FilePath path = GetProfileFileDirectory();
int pool_index = base::RandInt(0, 3);
std::string filename = base::StrCat(
{"child_pool-", base::NumberToString(pool_index), ".profraw"});
#if BUILDFLAG(IS_WIN)
path = path.Append(base::UTF8ToWide(filename));
#else
path = path.Append(filename);
#endif
uint32_t flags = base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ |
base::File::FLAG_WRITE;
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(path, flags);
if (!file.IsValid()) {
LOG(ERROR) << "Opening file: " << path << " failed with "
<< file.error_details();
}
return file;
}
}