Flutter Engine
fml Namespace Reference

Namespaces

 benchmarking
 
 icu
 
 internal
 
 jni
 
 paths
 
 state
 
 testing
 
 tracing
 

Classes

class  AsciiTrie
 A trie for looking for ASCII prefixes. More...
 
class  AtomicObject
 
class  AutoResetWaitableEvent
 
class  BitConverter
 
class  CFRef
 
class  CommandLine
 
class  ConcurrentMessageLoop
 
class  ConcurrentTaskRunner
 
class  CountDownLatch
 
class  DataMapping
 
struct  DebugTaskRunnerChecker
 
struct  DebugThreadChecker
 
class  DelayedTask
 
class  FileMapping
 
class  LogMessage
 
class  LogMessageVoidify
 
struct  LogSettings
 
class  ManualResetWaitableEvent
 
class  Mapping
 
class  Message
 
class  MessageLoop
 
class  MessageLoopAndroid
 
class  MessageLoopDarwin
 
class  MessageLoopFuchsia
 
class  MessageLoopImpl
 
class  MessageLoopLinux
 
class  MessageLoopTaskQueues
 
class  MessageLoopWin
 
class  MessageSerializable
 
class  NativeLibrary
 
class  NonOwnedMapping
 
class  PlatformSemaphore
 
class  RasterThreadMerger
 
class  RefCountedThreadSafe
 
class  RefPtr
 
class  scoped_nsobject
 
class  scoped_nsobject< id >
 
class  scoped_nsobject< NSAutoreleasePool >
 
class  scoped_nsprotocol
 
class  ScopedBlock
 
class  ScopedCleanupClosure
 Wraps a closure that is invoked in the destructor unless released by the caller. More...
 
class  ScopedSetLogSettings
 
class  ScopedTemporaryDirectory
 
class  Semaphore
 
struct  Serializable
 
class  SharedLock
 
class  SharedMutex
 
class  SharedMutexPosix
 
class  SharedMutexStd
 
class  Status
 
class  SymbolMapping
 
class  SyncSwitch
 
class  TaskQueueEntry
 
class  TaskQueueId
 
class  TaskRunner
 
class  TaskRunnerAffineWeakPtr
 
class  TaskRunnerAffineWeakPtrFactory
 
class  TaskRunnerChecker
 
struct  TestStruct
 
class  Thread
 
class  ThreadChecker
 
class  ThreadLocalUniquePtr
 
class  TimeDelta
 
class  TimePoint
 
class  UniqueLock
 
struct  UniqueLooperTraits
 
class  UniqueObject
 
class  Wakeable
 
class  WeakPtr
 
class  WeakPtrFactory
 

Typedefs

typedef AsciiTrie::TrieNode TrieNode
 
typedef AsciiTrie::TrieNodePtr TrieNodePtr
 
using Base32DecodeConverter = BitConverter< 5, 8, 16 >
 
using Base32EncodeConverter = BitConverter< 8, 5, 16 >
 
using closure = std::function< void()>
 
using DelayedTaskQueue = std::priority_queue< DelayedTask, std::deque< DelayedTask >, std::greater< DelayedTask > >
 
using FileVisitor = std::function< bool(const fml::UniqueFD &directory, const std::string &filename)>
 
typedef int LogSeverity
 
using WideStringConvertor = std::wstring_convert< std::codecvt_utf8_utf16< wchar_t >, wchar_t >
 
using Milliseconds = std::chrono::duration< double, std::milli >
 
using UniqueFD = UniqueObject< int, internal::os_unix::UniqueFDTraits >
 
using UniqueDir = UniqueObject< DIR *, internal::os_unix::UniqueDirTraits >
 

Enumerations

enum  FilePermission {
  FilePermission::kRead,
  FilePermission::kWrite,
  FilePermission::kReadWrite
}
 
enum  FlushType {
  FlushType::kSingle,
  FlushType::kAll
}
 
enum  OwnershipPolicy {
  OwnershipPolicy::Assume,
  OwnershipPolicy::Retain
}
 
enum  RasterThreadStatus {
  RasterThreadStatus::kRemainsMerged,
  RasterThreadStatus::kRemainsUnmerged,
  RasterThreadStatus::kUnmergedNow
}
 
enum  StatusCode {
  StatusCode::kOk,
  StatusCode::kCancelled,
  StatusCode::kUnknown,
  StatusCode::kInvalidArgument,
  StatusCode::kDeadlineExceeded,
  StatusCode::kNotFound,
  StatusCode::kAlreadyExists,
  StatusCode::kPermissionDenied,
  StatusCode::kResourceExhausted,
  StatusCode::kFailedPrecondition,
  StatusCode::kAborted,
  StatusCode::kOutOfRange,
  StatusCode::kUnimplemented,
  StatusCode::kInternal,
  StatusCode::kUnavailable,
  StatusCode::kDataLoss,
  StatusCode::kUnauthenticated
}
 

Functions

static std::string DemangleSymbolName (const std::string &mangled)
 
static std::string GetSymbolName (void *symbol)
 
std::string BacktraceHere (size_t offset)
 
static std::string SignalNameToString (int signal)
 
static void ToggleSignalHandlers (bool set)
 
static void SignalHandler (int signal)
 
void InstallCrashHandler ()
 
bool IsCrashHandlingSupported ()
 
std::pair< bool, std::string > Base32Encode (std::string_view input)
 
std::pair< bool, std::string > Base32Decode (const std::string &input)
 
std::vector< std::string > CommandLineToArgv (const CommandLine &command_line)
 
template<typename InputIterator >
CommandLine CommandLineFromIteratorsFindFirstPositionalArg (InputIterator first, InputIterator last, InputIterator *first_positional_arg)
 
template<typename InputIterator >
CommandLine CommandLineFromIterators (InputIterator first, InputIterator last)
 
template<typename InputIterator >
CommandLine CommandLineFromIteratorsWithArgv0 (const std::string &argv0, InputIterator first, InputIterator last)
 
CommandLine CommandLineFromArgcArgv (int argc, const char *const *argv)
 
template<typename StringType >
CommandLine CommandLineFromInitializerList (std::initializer_list< StringType > argv)
 
static fml::UniqueFD CreateDirectory (const fml::UniqueFD &base_directory, const std::vector< std::string > &components, FilePermission permission, size_t index)
 
fml::UniqueFD CreateDirectory (const fml::UniqueFD &base_directory, const std::vector< std::string > &components, FilePermission permission)
 
bool VisitFilesRecursively (const fml::UniqueFD &directory, const FileVisitor &visitor)
 
fml::UniqueFD OpenFileReadOnly (const fml::UniqueFD &base_directory, const char *path)
 
fml::UniqueFD OpenDirectoryReadOnly (const fml::UniqueFD &base_directory, const char *path)
 
bool RemoveFilesInDirectory (const fml::UniqueFD &directory)
 
bool RemoveDirectoryRecursively (const fml::UniqueFD &parent, const char *directory_name)
 
std::string CreateTemporaryDirectory ()
 
fml::UniqueFD OpenFile (const char *path, bool create_if_necessary, FilePermission permission)
 This can open a directory on POSIX, but not on Windows. More...
 
fml::UniqueFD OpenFile (const fml::UniqueFD &base_directory, const char *path, bool create_if_necessary, FilePermission permission)
 This can open a directory on POSIX, but not on Windows. More...
 
fml::UniqueFD OpenDirectory (const char *path, bool create_if_necessary, FilePermission permission)
 
fml::UniqueFD OpenDirectory (const fml::UniqueFD &base_directory, const char *path, bool create_if_necessary, FilePermission permission)
 
fml::UniqueFD Duplicate (fml::UniqueFD::element_type descriptor)
 
bool IsDirectory (const fml::UniqueFD &directory)
 
bool IsDirectory (const fml::UniqueFD &base_directory, const char *path)
 
bool IsFile (const std::string &path)
 
bool TruncateFile (const fml::UniqueFD &file, size_t size)
 
bool FileExists (const fml::UniqueFD &base_directory, const char *path)
 
bool UnlinkDirectory (const char *path)
 
bool UnlinkDirectory (const fml::UniqueFD &base_directory, const char *path)
 
bool UnlinkFile (const char *path)
 
bool UnlinkFile (const fml::UniqueFD &base_directory, const char *path)
 
bool WriteAtomically (const fml::UniqueFD &base_directory, const char *file_name, const Mapping &mapping)
 
bool VisitFiles (const fml::UniqueFD &directory, const FileVisitor &visitor)
 
template<class Type >
constexpr void HashCombineSeed (std::size_t &seed, Type arg)
 
template<class Type , class... Rest>
constexpr void HashCombineSeed (std::size_t &seed, Type arg, Rest... other_args)
 
constexpr std::size_t HashCombine ()
 
template<class... Type>
constexpr std::size_t HashCombine (Type... args)
 
void SetLogSettings (const LogSettings &settings)
 
LogSettings GetLogSettings ()
 
int GetMinLogLevel ()
 
int GetVlogVerbosity ()
 
bool ShouldCreateLogMessage (LogSeverity severity)
 
void KillProcess ()
 
template<typename T >
internal::CopyableLambda< T > MakeCopyable (T lambda)
 
template<typename T >
RefPtr< T > AdoptRef (T *ptr)
 
template<typename T >
RefPtr< T > Ref (T *ptr)
 
template<typename T , typename... Args>
RefPtr< T > MakeRefCounted (Args &&... args)
 
static uint32_t NextPowerOfTwoSize (uint32_t x)
 
 TEST (MessageTest, CanEncodeTriviallyCopyableTypes)
 
 TEST (MessageTest, CanDecodeTriviallyCopyableTypes)
 
static ALooper * AcquireLooperForThread ()
 
bool IsPlatformVersionAtLeast (size_t major, size_t minor=0, size_t patch=0)
 
template<class C >
void swap (scoped_nsprotocol< C > &p1, scoped_nsprotocol< C > &p2)
 
template<class C >
bool operator== (C p1, const scoped_nsprotocol< C > &p2)
 
template<class C >
bool operator!= (C p1, const scoped_nsprotocol< C > &p2)
 
NSRange RangeForCharacterAtIndex (NSString *text, NSUInteger index)
 
NSRange RangeForCharactersInRange (NSString *text, NSRange range)
 
bool TimerRearm (int fd, fml::TimePoint time_point)
 Rearms the timer to expire at the given time point. More...
 
bool TimerDrain (int fd)
 
static int ToPosixAccessFlags (FilePermission permission)
 
static int ToPosixCreateModeFlags (FilePermission permission)
 
static int ToPosixProtectionFlags (std::initializer_list< FileMapping::Protection > protection_flags)
 
static bool IsWritable (std::initializer_list< FileMapping::Protection > protection_flags)
 
char * strdup (const char *str1)
 
std::string GetLastErrorMessage ()
 
static std::string GetFullHandlePath (const fml::UniqueFD &handle)
 
static std::string GetAbsolutePath (const fml::UniqueFD &base_directory, const char *subpath)
 
static std::wstring GetTemporaryDirectoryPath ()
 
static DWORD GetDesiredAccessFlags (FilePermission permission)
 
static DWORD GetShareFlags (FilePermission permission)
 
static DWORD GetFileAttributesForUtf8Path (const char *absolute_path)
 
static DWORD GetFileAttributesForUtf8Path (const fml::UniqueFD &base_directory, const char *path)
 
static bool IsWritable (std::initializer_list< FileMapping::Protection > protection_flags)
 
static bool IsExecutable (std::initializer_list< FileMapping::Protection > protection_flags)
 
std::wstring StringToWideString (const std::string &str)
 
std::string WideStringToString (const std::wstring &wstr)
 
template<typename T , std::size_t N>
constexpr std::size_t size (T(&array)[N])
 
 TEST (CountDownLatchTest, CanWaitOnZero)
 
 TEST (CountDownLatchTest, CanWait)
 
template<typename ConditionFn >
bool WaitWithTimeoutImpl (std::unique_lock< std::mutex > *locker, std::condition_variable *cv, ConditionFn condition, TimeDelta timeout)
 
template<typename T >
Milliseconds RefreshRateToFrameBudget (T refresh_rate)
 
template<class T , class Traits >
void swap (const UniqueObject< T, Traits > &a, const UniqueObject< T, Traits > &b)
 
template<class T , class Traits >
bool operator== (const T &value, const UniqueObject< T, Traits > &object)
 
template<class T , class Traits >
bool operator!= (const T &value, const UniqueObject< T, Traits > &object)
 

Variables

static std::string kKUnknownFrameName = "Unknown"
 
static size_t kKnownSignalHandlers []
 
static std::string kKUnknownFrameName = "Unknown"
 
static constexpr char kEncoding [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
 
static constexpr signed char kDecodeMap []
 
static constexpr int kDecodeMapSize
 
constexpr LogSeverity LOG_INFO = 0
 
constexpr LogSeverity LOG_WARNING = 1
 
constexpr LogSeverity LOG_ERROR = 2
 
constexpr LogSeverity LOG_FATAL = 3
 
constexpr LogSeverity LOG_NUM_SEVERITIES = 4
 
const LogSeverity LOG_DFATAL = LOG_FATAL
 
FML_THREAD_LOCAL ThreadLocalUniquePtr< MessageLooptls_message_loop
 
static const TaskQueueId _kUnmerged = TaskQueueId(TaskQueueId::kUnmerged)
 
static constexpr int kClockType = CLOCK_MONOTONIC
 
static constexpr CFTimeInterval kDistantFuture = 1.0e10
 
static constexpr int kClockType = CLOCK_MONOTONIC
 
constexpr Milliseconds kDefaultFrameBudget = Milliseconds(1s) / 60
 

Typedef Documentation

◆ Base32DecodeConverter

using fml::Base32DecodeConverter = typedef BitConverter<5, 8, 16>

Definition at line 49 of file base32.h.

◆ Base32EncodeConverter

using fml::Base32EncodeConverter = typedef BitConverter<8, 5, 16>

Definition at line 50 of file base32.h.

◆ closure

using fml::closure = typedef std::function<void()>

Definition at line 14 of file closure.h.

◆ DelayedTaskQueue

using fml::DelayedTaskQueue = typedef std::priority_queue<DelayedTask, std::deque<DelayedTask>, std::greater<DelayedTask> >

Definition at line 39 of file delayed_task.h.

◆ FileVisitor

using fml::FileVisitor = typedef std::function<bool(const fml::UniqueFD& directory, const std::string& filename)>

Signature of a callback on a file in directory with filename (relative to directory). The returned bool should be false if and only if further traversal should be stopped. For example, a file-search visitor may return false when the file is found so no more visiting is needed.

Definition at line 98 of file file.h.

◆ LogSeverity

typedef int fml::LogSeverity

Definition at line 10 of file log_level.h.

◆ Milliseconds

using fml::Milliseconds = typedef std::chrono::duration<double, std::milli>

Definition at line 18 of file time_delta.h.

◆ TrieNode

Definition at line 10 of file ascii_trie.cc.

◆ TrieNodePtr

Definition at line 11 of file ascii_trie.cc.

◆ UniqueDir

Definition at line 62 of file unique_fd.h.

◆ UniqueFD

Definition at line 61 of file unique_fd.h.

◆ WideStringConvertor

using fml::WideStringConvertor = typedef std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>

Definition at line 15 of file wstring_conversion.h.

Enumeration Type Documentation

◆ FilePermission

enum fml::FilePermission
strong
Enumerator
kRead 
kWrite 
kReadWrite 

Definition at line 24 of file file.h.

◆ FlushType

enum fml::FlushType
strong
Enumerator
kSingle 
kAll 

Definition at line 57 of file message_loop_task_queues.h.

57  {
58  kSingle,
59  kAll,
60 };

◆ OwnershipPolicy

enum fml::OwnershipPolicy
strong
Enumerator
Assume 
Retain 

Definition at line 17 of file scoped_block.h.

17  {
18  // The scoped object takes ownership of an object by taking over an existing
19  // ownership claim.
20  Assume,
21 
22  // The scoped object will retain the object and any initial ownership is
23  // not changed.
24  Retain,
25 };

◆ RasterThreadStatus

Enumerator
kRemainsMerged 
kRemainsUnmerged 
kUnmergedNow 

Definition at line 19 of file raster_thread_merger.h.

◆ StatusCode

enum fml::StatusCode
strong
Enumerator
kOk 
kCancelled 
kUnknown 
kInvalidArgument 
kDeadlineExceeded 
kNotFound 
kAlreadyExists 
kPermissionDenied 
kResourceExhausted 
kFailedPrecondition 
kAborted 
kOutOfRange 
kUnimplemented 
kInternal 
kUnavailable 
kDataLoss 
kUnauthenticated 

Definition at line 12 of file status.h.

Function Documentation

◆ AcquireLooperForThread()

static ALooper* fml::AcquireLooperForThread ( )
static

Definition at line 16 of file message_loop_android.cc.

References FML_CHECK, FML_DCHECK, fml::UniqueObject< T, Traits >::get(), fml::MessageLoopImpl::RunExpiredTasksNow(), TFD_CLOEXEC, TFD_NONBLOCK, TimerDrain(), timerfd_create(), and TimerRearm().

16  {
17  ALooper* looper = ALooper_forThread();
18 
19  if (looper == nullptr) {
20  // No looper has been configured for the current thread. Create one and
21  // return the same.
22  looper = ALooper_prepare(0);
23  }
24 
25  // The thread already has a looper. Acquire a reference to the same and return
26  // it.
27  ALooper_acquire(looper);
28  return looper;
29 }

◆ AdoptRef()

template<typename T >
RefPtr< T > fml::AdoptRef ( T *  ptr)
inline

Definition at line 218 of file ref_ptr.h.

Referenced by fml::NativeLibrary::Create(), fml::NativeLibrary::CreateForCurrentProcess(), and fml::NativeLibrary::CreateWithHandle().

218  {
219 #ifndef NDEBUG
220  ptr->Adopt();
221 #endif
222  return RefPtr<T>(ptr, RefPtr<T>::ADOPT);
223 }

◆ BacktraceHere()

std::string fml::BacktraceHere ( size_t  offset = 0)

Definition at line 57 of file backtrace.cc.

References GetSymbolName().

Referenced by SignalHandler(), and fml::testing::TEST().

57  {
58  constexpr size_t kMaxFrames = 256;
59  void* symbols[kMaxFrames];
60  const auto available_frames = ::backtrace(symbols, kMaxFrames);
61  if (available_frames <= 0) {
62  return "";
63  }
64 
65  std::stringstream stream;
66  for (int i = 1 + offset; i < available_frames; ++i) {
67  stream << "Frame " << i - 1 - offset << ": " << symbols[i] << " "
68  << GetSymbolName(symbols[i]) << std::endl;
69  }
70  return stream.str();
71 }
static std::string GetSymbolName(void *symbol)
Definition: backtrace.cc:47

◆ Base32Decode()

std::pair< bool, std::string > fml::Base32Decode ( const std::string &  input)

Definition at line 54 of file base32.cc.

References fml::BitConverter< from_length, to_length, buffer_length >::Append(), fml::BitConverter< from_length, to_length, buffer_length >::CanExtract(), fml::BitConverter< from_length, to_length, buffer_length >::Extract(), and fml::BitConverter< from_length, to_length, buffer_length >::Peek().

Referenced by flutter::ParseBase32(), and TEST().

54  {
55  std::string result;
56  Base32DecodeConverter converter;
57  for (char c : input) {
58  int map_index = c - '2';
59  if (map_index < 0 || map_index >= kDecodeMapSize ||
60  kDecodeMap[map_index] == -1) {
61  return {false, result};
62  }
63  converter.Append(kDecodeMap[map_index]);
64  if (converter.CanExtract()) {
65  result.push_back(converter.Extract());
66  }
67  }
68  if (converter.Peek() != 0) {
69  // The padding should always be zero. Return false if not.
70  return {false, result};
71  }
72  return {true, result};
73 }
BitConverter< 5, 8, 16 > Base32DecodeConverter
Definition: base32.h:49
static constexpr int kDecodeMapSize
Definition: base32.cc:51
static constexpr signed char kDecodeMap[]
Definition: base32.cc:45

◆ Base32Encode()

std::pair< bool, std::string > fml::Base32Encode ( std::string_view  input)

Definition at line 14 of file base32.cc.

References fml::BitConverter< from_length, to_length, buffer_length >::Append(), fml::BitConverter< from_length, to_length, buffer_length >::BitsAvailable(), fml::BitConverter< from_length, to_length, buffer_length >::CanAppend(), fml::BitConverter< from_length, to_length, buffer_length >::CanExtract(), fml::BitConverter< from_length, to_length, buffer_length >::Extract(), and fml::BitConverter< from_length, to_length, buffer_length >::Peek().

Referenced by flutter::PersistentCache::SkKeyToFilePath(), and TEST().

14  {
15  if (input.empty()) {
16  return {true, ""};
17  }
18 
19  if (input.size() > std::numeric_limits<size_t>::max() / 8) {
20  return {false, ""};
21  }
22 
23  std::string output;
24  const size_t encoded_length = (input.size() * 8 + 4) / 5;
25  output.reserve(encoded_length);
26 
27  Base32EncodeConverter converter;
28  converter.Append(input[0]);
29  size_t next_byte_index = 1;
30 
31  while (converter.CanExtract()) {
32  output.push_back(kEncoding[converter.Extract()]);
33  if (converter.CanAppend() && next_byte_index < input.size()) {
34  converter.Append(static_cast<uint8_t>(input[next_byte_index++]));
35  }
36  }
37 
38  if (converter.BitsAvailable() > 0) {
39  output.push_back(kEncoding[converter.Peek()]);
40  }
41 
42  return {true, output};
43 }
BitConverter< 8, 5, 16 > Base32EncodeConverter
Definition: base32.h:50
static constexpr char kEncoding[]
Definition: base32.cc:12

◆ CommandLineFromArgcArgv()

CommandLine fml::CommandLineFromArgcArgv ( int  argc,
const char *const *  argv 
)
inline

Definition at line 222 of file command_line.h.

References CommandLineFromIterators().

Referenced by FlutterEngineInitialize(), GetTestTimeoutFromArgs(), and main().

222  {
223  return CommandLineFromIterators(argv, argv + argc);
224 }
CommandLine CommandLineFromIterators(InputIterator first, InputIterator last)
Definition: command_line.h:201

◆ CommandLineFromInitializerList()

template<typename StringType >
CommandLine fml::CommandLineFromInitializerList ( std::initializer_list< StringType >  argv)
inline

Definition at line 229 of file command_line.h.

References CommandLineFromIterators(), and CommandLineToArgv().

230  {
231  return CommandLineFromIterators(argv.begin(), argv.end());
232 }
CommandLine CommandLineFromIterators(InputIterator first, InputIterator last)
Definition: command_line.h:201

◆ CommandLineFromIterators()

template<typename InputIterator >
CommandLine fml::CommandLineFromIterators ( InputIterator  first,
InputIterator  last 
)
inline

Definition at line 201 of file command_line.h.

Referenced by CommandLineFromArgcArgv(), CommandLineFromInitializerList(), flutter::CommandLineFromNSProcessInfo(), and flutter::FlutterMain::GetSettings().

202  {
203  return CommandLineFromIteratorsFindFirstPositionalArg<InputIterator>(
204  first, last, nullptr);
205 }

◆ CommandLineFromIteratorsFindFirstPositionalArg()

template<typename InputIterator >
CommandLine fml::CommandLineFromIteratorsFindFirstPositionalArg ( InputIterator  first,
InputIterator  last,
InputIterator *  first_positional_arg 
)
inline

Definition at line 181 of file command_line.h.

References fml::internal::CommandLineBuilder::Build(), and fml::internal::CommandLineBuilder::ProcessArg().

184  {
185  if (first_positional_arg)
186  *first_positional_arg = last;
187  internal::CommandLineBuilder builder;
188  for (auto it = first; it < last; ++it) {
189  if (builder.ProcessArg(*it)) {
190  if (first_positional_arg)
191  *first_positional_arg = it;
192  }
193  }
194  return builder.Build();
195 }

◆ CommandLineFromIteratorsWithArgv0()

template<typename InputIterator >
CommandLine fml::CommandLineFromIteratorsWithArgv0 ( const std::string &  argv0,
InputIterator  first,
InputIterator  last 
)
inline

Definition at line 211 of file command_line.h.

References fml::internal::CommandLineBuilder::Build(), and fml::internal::CommandLineBuilder::ProcessArg().

213  {
214  internal::CommandLineBuilder builder;
215  builder.ProcessArg(argv0);
216  for (auto it = first; it < last; ++it)
217  builder.ProcessArg(*it);
218  return builder.Build();
219 }

◆ CommandLineToArgv()

std::vector< std::string > fml::CommandLineToArgv ( const CommandLine command_line)

Definition at line 141 of file command_line.cc.

References fml::CommandLine::argv0(), fml::CommandLine::has_argv0(), fml::CommandLine::options(), fml::CommandLine::positional_args(), and size().

Referenced by CommandLineFromInitializerList().

141  {
142  if (!command_line.has_argv0()) {
143  return std::vector<std::string>();
144  }
145 
146  std::vector<std::string> argv;
147  const std::vector<CommandLine::Option>& options = command_line.options();
148  const std::vector<std::string>& positional_args =
149  command_line.positional_args();
150  // Reserve space for argv[0], options, maybe a "--" (if needed), and the
151  // positional arguments.
152  argv.reserve(1u + options.size() + 1u + positional_args.size());
153 
154  argv.push_back(command_line.argv0());
155  for (const auto& option : options) {
156  if (option.value.empty()) {
157  argv.push_back("--" + option.name);
158  } else {
159  argv.push_back("--" + option.name + "=" + option.value);
160  }
161  }
162 
163  if (!positional_args.empty()) {
164  // Insert a "--" if necessary.
165  if (positional_args[0].size() >= 2u && positional_args[0][0] == '-' &&
166  positional_args[0][1] == '-') {
167  argv.push_back("--");
168  }
169 
170  argv.insert(argv.end(), positional_args.begin(), positional_args.end());
171  }
172 
173  return argv;
174 }
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13

◆ CreateDirectory() [1/2]

static fml::UniqueFD fml::CreateDirectory ( const fml::UniqueFD base_directory,
const std::vector< std::string > &  components,
FilePermission  permission,
size_t  index 
)
static

Definition at line 12 of file file.cc.

References FML_DCHECK, and OpenDirectory().

Referenced by CreateDirectory(), GetFileAttributesForUtf8Path(), flutter::PersistentCache::Purge(), filesystem::TEST(), TEST(), and flutter::testing::TEST_F().

15  {
16  FML_DCHECK(index <= components.size());
17 
18  const char* file_path = components[index].c_str();
19 
20  auto directory = OpenDirectory(base_directory, file_path, true, permission);
21 
22  if (!directory.is_valid()) {
23  return {};
24  }
25 
26  if (index == components.size() - 1) {
27  return directory;
28  }
29 
30  return CreateDirectory(directory, components, permission, index + 1);
31 }
#define FML_DCHECK(condition)
Definition: logging.h:86
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
Definition: file_posix.cc:94
fml::UniqueFD CreateDirectory(const fml::UniqueFD &base_directory, const std::vector< std::string > &components, FilePermission permission)
Definition: file.cc:33

◆ CreateDirectory() [2/2]

fml::UniqueFD fml::CreateDirectory ( const fml::UniqueFD base_directory,
const std::vector< std::string > &  components,
FilePermission  permission 
)

Definition at line 33 of file file.cc.

References CreateDirectory(), and IsDirectory().

35  {
36  if (!IsDirectory(base_directory)) {
37  return {};
38  }
39 
40  if (components.size() == 0) {
41  return {};
42  }
43 
44  return CreateDirectory(base_directory, components, permission, 0);
45 }
fml::UniqueFD CreateDirectory(const fml::UniqueFD &base_directory, const std::vector< std::string > &components, FilePermission permission)
Definition: file.cc:33
bool IsDirectory(const fml::UniqueFD &directory)
Definition: file_posix.cc:124

◆ CreateTemporaryDirectory()

std::string fml::CreateTemporaryDirectory ( )

Definition at line 23 of file file_posix.cc.

Referenced by GetFileAttributesForUtf8Path(), and TEST().

23  {
24  char directory_name[] = "/tmp/flutter_XXXXXXXX";
25  auto* result = ::mkdtemp(directory_name);
26  if (result == nullptr) {
27  return "";
28  }
29  return {result};
30 }

◆ DemangleSymbolName()

static std::string fml::DemangleSymbolName ( const std::string &  mangled)
static

Definition at line 25 of file backtrace.cc.

References kKUnknownFrameName, and length.

Referenced by GetSymbolName().

25  {
26  if (mangled == kKUnknownFrameName) {
27  return kKUnknownFrameName;
28  }
29 
30  int status = 0;
31  size_t length = 0;
32  char* demangled = __cxxabiv1::__cxa_demangle(
33  mangled.data(), // mangled name
34  nullptr, // output buffer (malloc-ed if nullptr)
35  &length, // demangled length
36  &status);
37 
38  if (demangled == nullptr || status != 0) {
39  return mangled;
40  }
41 
42  auto demangled_string = std::string{demangled, length};
43  free(demangled);
44  return demangled_string;
45 }
static std::string kKUnknownFrameName
Definition: backtrace.cc:23
size_t length

◆ Duplicate()

◆ FileExists()

bool fml::FileExists ( const fml::UniqueFD base_directory,
const char *  path 
)

Definition at line 180 of file file_posix.cc.

References fml::UniqueObject< T, Traits >::get(), fml::UniqueObject< T, Traits >::is_valid(), and flutter::path.

Referenced by GetFileAttributesForUtf8Path(), OpenDirectory(), OpenFile(), and TEST().

180  {
181  if (!base_directory.is_valid()) {
182  return false;
183  }
184 
185  return ::faccessat(base_directory.get(), path, F_OK, 0) == 0;
186 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
const T & get() const
Definition: unique_object.h:87
bool is_valid() const
Definition: unique_object.h:89

◆ GetAbsolutePath()

static std::string fml::GetAbsolutePath ( const fml::UniqueFD base_directory,
const char *  subpath 
)
static

Definition at line 35 of file file_win.cc.

References GetFullHandlePath(), and flutter::path.

Referenced by GetFileAttributesForUtf8Path().

36  {
37  std::stringstream stream;
38  stream << GetFullHandlePath(base_directory) << "\\" << subpath;
39  auto path = stream.str();
40  std::replace(path.begin(), path.end(), '/', '\\');
41  return path;
42 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
static std::string GetFullHandlePath(const fml::UniqueFD &handle)
Definition: file_win.cc:23

◆ GetDesiredAccessFlags()

static DWORD fml::GetDesiredAccessFlags ( FilePermission  permission)
static

Definition at line 55 of file file_win.cc.

References kRead, kReadWrite, and kWrite.

Referenced by GetFileAttributesForUtf8Path().

55  {
56  switch (permission) {
57  case FilePermission::kRead:
58  return GENERIC_READ;
59  case FilePermission::kWrite:
60  return GENERIC_WRITE;
61  case FilePermission::kReadWrite:
62  return GENERIC_READ | GENERIC_WRITE;
63  }
64  return GENERIC_READ;
65 }

◆ GetFileAttributesForUtf8Path() [1/2]

static DWORD fml::GetFileAttributesForUtf8Path ( const char *  absolute_path)
static

Definition at line 79 of file file_win.cc.

References StringToWideString().

Referenced by GetFileAttributesForUtf8Path().

79  {
80  return ::GetFileAttributes(StringToWideString(absolute_path).c_str());
81 }
std::wstring StringToWideString(const std::string &str)

◆ GetFileAttributesForUtf8Path() [2/2]

static DWORD fml::GetFileAttributesForUtf8Path ( const fml::UniqueFD base_directory,
const char *  path 
)
static

◆ GetFullHandlePath()

static std::string fml::GetFullHandlePath ( const fml::UniqueFD handle)
static

Definition at line 23 of file file_win.cc.

References FML_DLOG, fml::UniqueObject< T, Traits >::get(), GetLastErrorMessage(), and WideStringToString().

Referenced by GetAbsolutePath(), and GetFileAttributesForUtf8Path().

23  {
24  wchar_t buffer[MAX_PATH] = {0};
25  const DWORD buffer_size = ::GetFinalPathNameByHandle(
26  handle.get(), buffer, MAX_PATH, FILE_NAME_NORMALIZED);
27  if (buffer_size == 0) {
28  FML_DLOG(ERROR) << "Could not get file handle path. "
30  return {};
31  }
32  return WideStringToString({buffer, buffer_size});
33 }
const T & get() const
Definition: unique_object.h:87
#define FML_DLOG(severity)
Definition: logging.h:85
std::string GetLastErrorMessage()
Definition: errors_win.cc:15
std::string WideStringToString(const std::wstring &wstr)

◆ GetLastErrorMessage()

std::string fml::GetLastErrorMessage ( )

Definition at line 15 of file errors_win.cc.

References flutter::flags, size(), and WideStringToString().

Referenced by GetFileAttributesForUtf8Path(), GetFullHandlePath(), and GetTemporaryDirectoryPath().

15  {
16  DWORD last_error = ::GetLastError();
17  if (last_error == 0) {
18  return {};
19  }
20 
21  const DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
22  FORMAT_MESSAGE_FROM_SYSTEM |
23  FORMAT_MESSAGE_IGNORE_INSERTS;
24 
25  wchar_t* buffer = nullptr;
26  size_t size = ::FormatMessage(
27  flags, // dwFlags
28  NULL, // lpSource
29  last_error, // dwMessageId
30  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // dwLanguageId
31  (LPWSTR)&buffer, // lpBuffer
32  0, // nSize
33  NULL // Arguments
34  );
35 
36  std::wstring message(buffer, size);
37 
38  ::LocalFree(buffer);
39 
40  std::wstringstream stream;
41  stream << message << " (" << last_error << ").";
42 
43  return WideStringToString(stream.str());
44 }
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
std::string WideStringToString(const std::wstring &wstr)
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66

◆ GetLogSettings()

LogSettings fml::GetLogSettings ( )

Definition at line 29 of file log_settings.cc.

References fml::state::g_log_settings.

Referenced by fml::ScopedSetLogSettings::ScopedSetLogSettings().

29  {
30  return state::g_log_settings;
31 }
LogSettings g_log_settings

◆ GetMinLogLevel()

int fml::GetMinLogLevel ( )

Definition at line 33 of file log_settings.cc.

References fml::state::g_log_settings, and LOG_FATAL.

Referenced by GetVlogVerbosity(), and ShouldCreateLogMessage().

33  {
34  return std::min(state::g_log_settings.min_log_level, LOG_FATAL);
35 }
LogSettings g_log_settings
constexpr LogSeverity LOG_FATAL
Definition: log_level.h:16

◆ GetShareFlags()

static DWORD fml::GetShareFlags ( FilePermission  permission)
static

Definition at line 67 of file file_win.cc.

References kRead, kReadWrite, and kWrite.

Referenced by GetFileAttributesForUtf8Path().

67  {
68  switch (permission) {
69  case FilePermission::kRead:
70  return FILE_SHARE_READ;
71  case FilePermission::kWrite:
72  return FILE_SHARE_WRITE;
73  case FilePermission::kReadWrite:
74  return FILE_SHARE_READ | FILE_SHARE_WRITE;
75  }
76  return FILE_SHARE_READ;
77 }

◆ GetSymbolName()

static std::string fml::GetSymbolName ( void *  symbol)
static

Definition at line 47 of file backtrace.cc.

References DemangleSymbolName(), and kKUnknownFrameName.

Referenced by BacktraceHere().

47  {
48  Dl_info info = {};
49 
50  if (::dladdr(symbol, &info) == 0) {
51  return kKUnknownFrameName;
52  }
53 
54  return DemangleSymbolName({info.dli_sname});
55 }
static std::string DemangleSymbolName(const std::string &mangled)
Definition: backtrace.cc:25
static std::string kKUnknownFrameName
Definition: backtrace.cc:23

◆ GetTemporaryDirectoryPath()

static std::wstring fml::GetTemporaryDirectoryPath ( )
static

Definition at line 44 of file file_win.cc.

References FML_DLOG, and GetLastErrorMessage().

Referenced by GetFileAttributesForUtf8Path().

44  {
45  wchar_t wchar_path[MAX_PATH];
46  auto result_size = ::GetTempPath(MAX_PATH, wchar_path);
47  if (result_size > 0) {
48  return {wchar_path, result_size};
49  }
50  FML_DLOG(ERROR) << "Could not get temporary directory path. "
52  return {};
53 }
#define FML_DLOG(severity)
Definition: logging.h:85
std::string GetLastErrorMessage()
Definition: errors_win.cc:15

◆ GetVlogVerbosity()

int fml::GetVlogVerbosity ( )

Definition at line 100 of file logging.cc.

References GetMinLogLevel(), and LOG_INFO.

Referenced by fml::LogMessage::stream().

100  {
101  return std::max(-1, LOG_INFO - GetMinLogLevel());
102 }
int GetMinLogLevel()
Definition: log_settings.cc:33
constexpr LogSeverity LOG_INFO
Definition: log_level.h:13

◆ HashCombine() [1/2]

constexpr std::size_t fml::HashCombine ( )

◆ HashCombine() [2/2]

template<class... Type>
constexpr std::size_t fml::HashCombine ( Type...  args)

Definition at line 30 of file hash_combine.h.

References args, HashCombine(), and HashCombineSeed().

30  {
31  std::size_t seed = HashCombine();
32  HashCombineSeed(seed, args...);
33  return seed;
34 }
constexpr std::size_t HashCombine(Type... args)
Definition: hash_combine.h:30
G_BEGIN_DECLS FlValue * args
constexpr void HashCombineSeed(std::size_t &seed, Type arg, Rest... other_args)
Definition: hash_combine.h:18

◆ HashCombineSeed() [1/2]

template<class Type >
constexpr void fml::HashCombineSeed ( std::size_t &  seed,
Type  arg 
)

Definition at line 13 of file hash_combine.h.

Referenced by HashCombine(), and HashCombineSeed().

13  {
14  seed ^= std::hash<Type>{}(arg) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
15 }

◆ HashCombineSeed() [2/2]

template<class Type , class... Rest>
constexpr void fml::HashCombineSeed ( std::size_t &  seed,
Type  arg,
Rest...  other_args 
)

Definition at line 18 of file hash_combine.h.

References HashCombineSeed().

20  {
21  HashCombineSeed(seed, arg);
22  HashCombineSeed(seed, other_args...);
23 }
constexpr void HashCombineSeed(std::size_t &seed, Type arg, Rest... other_args)
Definition: hash_combine.h:18

◆ InstallCrashHandler()

void fml::InstallCrashHandler ( )

Definition at line 133 of file backtrace.cc.

References ToggleSignalHandlers().

Referenced by benchmarking::Main(), and main().

133  {
134 #if OS_WIN
135  if (!IsDebuggerPresent()) {
136  _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
137  _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
138  }
139 #endif
140  ToggleSignalHandlers(true);
141 }
static void ToggleSignalHandlers(bool set)
Definition: backtrace.cc:122

◆ IsCrashHandlingSupported()

bool fml::IsCrashHandlingSupported ( )

Definition at line 143 of file backtrace.cc.

Referenced by fml::testing::TEST().

143  {
144  return true;
145 }

◆ IsDirectory() [1/2]

bool fml::IsDirectory ( const fml::UniqueFD directory)

Definition at line 124 of file file_posix.cc.

References fml::UniqueObject< T, Traits >::get(), and fml::UniqueObject< T, Traits >::is_valid().

Referenced by CreateDirectory(), flutter::DirectoryAssetBundle::DirectoryAssetBundle(), GetFileAttributesForUtf8Path(), IsDirectory(), flutter::PersistentCache::Purge(), RemoveFilesInDirectory(), filesystem::TEST(), flutter::testing::TEST_F(), and VisitFilesRecursively().

124  {
125  if (!directory.is_valid()) {
126  return false;
127  }
128 
129  struct stat stat_result = {};
130 
131  if (::fstat(directory.get(), &stat_result) != 0) {
132  return false;
133  }
134 
135  return S_ISDIR(stat_result.st_mode);
136 }
const T & get() const
Definition: unique_object.h:87
bool is_valid() const
Definition: unique_object.h:89

◆ IsDirectory() [2/2]

bool fml::IsDirectory ( const fml::UniqueFD base_directory,
const char *  path 
)

Definition at line 138 of file file_posix.cc.

References fml::UniqueObject< T, Traits >::is_valid(), IsDirectory(), and OpenFileReadOnly().

138  {
139  UniqueFD file = OpenFileReadOnly(base_directory, path);
140  return (file.is_valid() && IsDirectory(file));
141 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
UniqueObject< int, internal::os_unix::UniqueFDTraits > UniqueFD
Definition: unique_fd.h:61
bool IsDirectory(const fml::UniqueFD &directory)
Definition: file_posix.cc:124
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition: file.cc:92

◆ IsExecutable()

static bool fml::IsExecutable ( std::initializer_list< FileMapping::Protection protection_flags)
static

Definition at line 33 of file mapping_win.cc.

References fml::FileMapping::FileMapping(), and fml::FileMapping::kExecute.

34  {
35  for (auto protection : protection_flags) {
36  if (protection == FileMapping::Protection::kExecute) {
37  return true;
38  }
39  }
40  return false;
41 }

◆ IsFile()

bool fml::IsFile ( const std::string &  path)

Definition at line 143 of file file_posix.cc.

Referenced by FlutterEngineCreateAOTData(), FlutterEngineInitialize(), GetFileAttributesForUtf8Path(), flutter::FlutterMain::GetSettings(), flutter::testing::LoadELFSymbolFromFixturesIfNeccessary(), flutter::testing::RunDartCodeInIsolateOnUITaskRunner(), and TEST().

143  {
144  struct stat buf;
145  if (stat(path.c_str(), &buf) != 0) {
146  return false;
147  }
148 
149  return S_ISREG(buf.st_mode);
150 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32

◆ IsPlatformVersionAtLeast()

bool fml::IsPlatformVersionAtLeast ( size_t  major,
size_t  minor = 0,
size_t  patch = 0 
)

Definition at line 11 of file platform_version.mm.

11  {
12  const NSOperatingSystemVersion version = {
13  .majorVersion = static_cast<NSInteger>(major),
14  .minorVersion = static_cast<NSInteger>(minor),
15  .patchVersion = static_cast<NSInteger>(patch),
16  };
17  return [[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:version];
18 }

◆ IsWritable() [1/2]

static bool fml::IsWritable ( std::initializer_list< FileMapping::Protection protection_flags)
static

Definition at line 23 of file mapping_win.cc.

References fml::FileMapping::kWrite.

24  {
25  for (auto protection : protection_flags) {
26  if (protection == FileMapping::Protection::kWrite) {
27  return true;
28  }
29  }
30  return false;
31 }

◆ IsWritable() [2/2]

static bool fml::IsWritable ( std::initializer_list< FileMapping::Protection protection_flags)
static

Definition at line 39 of file mapping_posix.cc.

References fml::FileMapping::kWrite, fml::Mapping::Mapping(), and fml::Mapping::~Mapping().

40  {
41  for (auto protection : protection_flags) {
42  if (protection == FileMapping::Protection::kWrite) {
43  return true;
44  }
45  }
46  return false;
47 }

◆ KillProcess()

void fml::KillProcess ( )

◆ MakeCopyable()

◆ MakeRefCounted()

template<typename T , typename... Args>
RefPtr<T> fml::MakeRefCounted ( Args &&...  args)

Definition at line 244 of file ref_ptr.h.

References args, and fml::internal::MakeRefCountedHelper< T >::MakeRefCounted().

244  {
246  std::forward<Args>(args)...);
247 }
G_BEGIN_DECLS FlValue * args
RefPtr< T > MakeRefCounted(Args &&... args)
Definition: ref_ptr.h:244

◆ NextPowerOfTwoSize()

static uint32_t fml::NextPowerOfTwoSize ( uint32_t  x)
static

Definition at line 19 of file message.cc.

Referenced by fml::Message::GetSizeRead().

19  {
20  if (x == 0) {
21  return 1;
22  }
23 
24  --x;
25 
26  x |= x >> 1;
27  x |= x >> 2;
28  x |= x >> 4;
29  x |= x >> 8;
30  x |= x >> 16;
31 
32  return x + 1;
33 }

◆ OpenDirectory() [1/2]

◆ OpenDirectory() [2/2]

fml::UniqueFD fml::OpenDirectory ( const fml::UniqueFD base_directory,
const char *  path,
bool  create_if_necessary,
FilePermission  permission 
)

Definition at line 101 of file file_posix.cc.

References FileExists(), FML_HANDLE_EINTR, fml::UniqueObject< T, Traits >::get(), flutter::path, and ToPosixCreateModeFlags().

104  {
105  if (path == nullptr) {
106  return {};
107  }
108 
109  if (create_if_necessary && !FileExists(base_directory, path)) {
110  if (::mkdirat(base_directory.get(), path,
111  ToPosixCreateModeFlags(permission) | S_IXUSR) != 0) {
112  return {};
113  }
114  }
115 
117  ::openat(base_directory.get(), path, O_RDONLY | O_DIRECTORY))};
118 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
static int ToPosixCreateModeFlags(FilePermission permission)
Definition: file_posix.cc:48
const T & get() const
Definition: unique_object.h:87
#define FML_HANDLE_EINTR(x)
Definition: eintr_wrapper.h:33
bool FileExists(const fml::UniqueFD &base_directory, const char *path)
Definition: file_posix.cc:180

◆ OpenDirectoryReadOnly()

fml::UniqueFD fml::OpenDirectoryReadOnly ( const fml::UniqueFD base_directory,
const char *  path 
)

Helper method that calls OpenDirectory with create_if_necessary = false and permission = kRead.

Definition at line 97 of file file.cc.

References kRead, and OpenDirectory().

Referenced by flutter::PersistentCache::LoadSkSLs(), flutter::PersistentCache::Purge(), RemoveFilesInDirectory(), flutter::testing::TEST_F(), and VisitFilesRecursively().

98  {
99  return OpenDirectory(base_directory, path, false, FilePermission::kRead);
100 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
Definition: file_posix.cc:94

◆ OpenFile() [1/2]

fml::UniqueFD fml::OpenFile ( const char *  path,
bool  create_if_necessary,
FilePermission  permission 
)

This can open a directory on POSIX, but not on Windows.

Definition at line 64 of file file_posix.cc.

References flutter::path.

Referenced by fml::FileMapping::CreateReadExecute(), fml::FileMapping::CreateReadOnly(), flutter::DirectoryAssetBundle::DirectoryAssetBundle(), GetFileAttributesForUtf8Path(), flutter::GetVMServiceAssetsArchiveCallback(), OpenFileReadOnly(), flutter::testing::OpenFixture(), flutter::testing::RunDartCodeInIsolateOnUITaskRunner(), flutter::RunTester(), flutter::ServiceProtocolFailureError(), fml::icu::ICUContext::SetupMapping(), TEST(), and WriteAtomically().

66  {
67  return OpenFile(fml::UniqueFD{AT_FDCWD}, path, create_if_necessary,
68  permission);
69 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
fml::UniqueFD OpenFile(const char *path, bool create_if_necessary, FilePermission permission)
This can open a directory on POSIX, but not on Windows.
Definition: file_posix.cc:64

◆ OpenFile() [2/2]

fml::UniqueFD fml::OpenFile ( const fml::UniqueFD base_directory,
const char *  path,
bool  create_if_necessary,
FilePermission  permission 
)

This can open a directory on POSIX, but not on Windows.

Definition at line 71 of file file_posix.cc.

References FileExists(), flutter::flags, FML_HANDLE_EINTR, fml::UniqueObject< T, Traits >::get(), flutter::path, ToPosixAccessFlags(), and ToPosixCreateModeFlags().

74  {
75  if (path == nullptr) {
76  return {};
77  }
78 
79  int flags = 0;
80  int mode = 0;
81 
82  if (create_if_necessary && !FileExists(base_directory, path)) {
83  flags = ToPosixAccessFlags(permission) | O_CREAT | O_TRUNC;
84  mode = ToPosixCreateModeFlags(permission);
85  } else {
86  flags = ToPosixAccessFlags(permission);
87  mode = 0; // Not creating since it already exists.
88  }
89 
90  return fml::UniqueFD{
91  FML_HANDLE_EINTR(::openat(base_directory.get(), path, flags, mode))};
92 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
static int ToPosixCreateModeFlags(FilePermission permission)
Definition: file_posix.cc:48
const T & get() const
Definition: unique_object.h:87
#define FML_HANDLE_EINTR(x)
Definition: eintr_wrapper.h:33
bool FileExists(const fml::UniqueFD &base_directory, const char *path)
Definition: file_posix.cc:180
static int ToPosixAccessFlags(FilePermission permission)
Definition: file_posix.cc:32
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66

◆ OpenFileReadOnly()

fml::UniqueFD fml::OpenFileReadOnly ( const fml::UniqueFD base_directory,
const char *  path 
)

Helper method that calls OpenFile with create_if_necessary = false and permission = kRead.

This can open a directory on POSIX, but not on Windows.

Definition at line 92 of file file.cc.

References kRead, and OpenFile().

Referenced by IsDirectory(), flutter::PersistentCache::LoadSkSLs(), and flutter::testing::TEST_F().

93  {
94  return OpenFile(base_directory, path, false, FilePermission::kRead);
95 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
fml::UniqueFD OpenFile(const char *path, bool create_if_necessary, FilePermission permission)
This can open a directory on POSIX, but not on Windows.
Definition: file_posix.cc:64

◆ operator!=() [1/2]

template<class C >
bool fml::operator!= ( p1,
const scoped_nsprotocol< C > &  p2 
)

Definition at line 107 of file scoped_nsobject.h.

References fml::scoped_nsprotocol< NST >::get().

107  {
108  return p1 != p2.get();
109 }

◆ operator!=() [2/2]

template<class T , class Traits >
bool fml::operator!= ( const T &  value,
const UniqueObject< T, Traits > &  object 
)

Definition at line 131 of file unique_object.h.

131  {
132  return !(value == object.get());
133 }
uint8_t value

◆ operator==() [1/2]

template<class C >
bool fml::operator== ( p1,
const scoped_nsprotocol< C > &  p2 
)

Definition at line 102 of file scoped_nsobject.h.

References fml::scoped_nsprotocol< NST >::get().

102  {
103  return p1 == p2.get();
104 }

◆ operator==() [2/2]

template<class T , class Traits >
bool fml::operator== ( const T &  value,
const UniqueObject< T, Traits > &  object 
)

Definition at line 126 of file unique_object.h.

126  {
127  return value == object.get();
128 }
uint8_t value

◆ RangeForCharacterAtIndex()

NSRange fml::RangeForCharacterAtIndex ( NSString *  text,
NSUInteger  index 
)

Definition at line 9 of file string_range_sanitization.mm.

Referenced by TEST().

9  {
10  if (text == nil || index > text.length) {
11  return NSMakeRange(NSNotFound, 0);
12  }
13  if (index < text.length)
14  return [text rangeOfComposedCharacterSequenceAtIndex:index];
15  return NSMakeRange(index, 0);
16 }

◆ RangeForCharactersInRange()

NSRange fml::RangeForCharactersInRange ( NSString *  text,
NSRange  range 
)

Definition at line 18 of file string_range_sanitization.mm.

Referenced by TEST().

18  {
19  if (text == nil || range.location + range.length > text.length) {
20  return NSMakeRange(NSNotFound, 0);
21  }
22  NSRange sanitizedRange = [text rangeOfComposedCharacterSequencesForRange:range];
23  // We don't want to override the length, we just want to make sure we don't
24  // select into the middle of a multi-byte character. Taking the
25  // `sanitizedRange`'s length will end up altering the actual selection.
26  return NSMakeRange(sanitizedRange.location, range.length);
27 }

◆ Ref()

template<typename T >
RefPtr<T> fml::Ref ( T *  ptr)
inline

Definition at line 233 of file ref_ptr.h.

Referenced by flutter::SkiaUnrefQueue::Unref().

233  {
234  return RefPtr<T>(ptr);
235 }

◆ RefreshRateToFrameBudget()

template<typename T >
Milliseconds fml::RefreshRateToFrameBudget ( refresh_rate)

Definition at line 24 of file time_delta.h.

Referenced by flutter::Shell::GetDartVM().

24  {
25  return Milliseconds(1s) / refresh_rate;
26 }
std::chrono::duration< double, std::milli > Milliseconds
Definition: time_delta.h:18

◆ RemoveDirectoryRecursively()

bool fml::RemoveDirectoryRecursively ( const fml::UniqueFD parent,
const char *  directory_name 
)

Helper method to recursively remove files and subdirectories inside the directory. The directory itself will also be removed.

Return true if and only if all files have been successfully removed.

Definition at line 120 of file file.cc.

References kReadWrite, OpenDirectory(), RemoveFilesInDirectory(), and UnlinkDirectory().

Referenced by flutter::PersistentCache::Purge().

121  {
122  auto dir = fml::OpenDirectory(parent, directory_name, false,
124  return RemoveFilesInDirectory(dir) && UnlinkDirectory(parent, directory_name);
125 }
bool RemoveFilesInDirectory(const fml::UniqueFD &directory)
Definition: file.cc:102
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
Definition: file_posix.cc:94
bool UnlinkDirectory(const char *path)
Definition: file_posix.cc:160

◆ RemoveFilesInDirectory()

bool fml::RemoveFilesInDirectory ( const fml::UniqueFD directory)

Helper method to recursively remove files and subdirectories inside the directory. The directory itself will not be removed.

Return true if and only if all files have been successfully removed.

Definition at line 102 of file file.cc.

References IsDirectory(), OpenDirectoryReadOnly(), UnlinkDirectory(), UnlinkFile(), and VisitFiles().

Referenced by RemoveDirectoryRecursively(), flutter::testing::TEST_F(), and fml::ScopedTemporaryDirectory::~ScopedTemporaryDirectory().

102  {
103  fml::FileVisitor recursive_cleanup = [&recursive_cleanup](
104  const fml::UniqueFD& directory,
105  const std::string& filename) {
106  bool removed;
107  if (fml::IsDirectory(directory, filename.c_str())) {
108  fml::UniqueFD sub_dir =
109  OpenDirectoryReadOnly(directory, filename.c_str());
110  removed = VisitFiles(sub_dir, recursive_cleanup) &&
111  fml::UnlinkDirectory(directory, filename.c_str());
112  } else {
113  removed = fml::UnlinkFile(directory, filename.c_str());
114  }
115  return removed;
116  };
117  return VisitFiles(directory, recursive_cleanup);
118 }
std::function< bool(const fml::UniqueFD &directory, const std::string &filename)> FileVisitor
Definition: file.h:98
bool VisitFiles(const fml::UniqueFD &directory, const FileVisitor &visitor)
Definition: file_posix.cc:233
bool IsDirectory(const fml::UniqueFD &directory)
Definition: file_posix.cc:124
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition: file.cc:97
bool UnlinkFile(const char *path)
Definition: file_posix.cc:168
bool UnlinkDirectory(const char *path)
Definition: file_posix.cc:160

◆ SetLogSettings()

void fml::SetLogSettings ( const LogSettings settings)

Definition at line 23 of file log_settings.cc.

References fml::state::g_log_settings, LOG_FATAL, and fml::LogSettings::min_log_level.

Referenced by flutter::PerformInitializationTasks(), fml::ScopedSetLogSettings::ScopedSetLogSettings(), and fml::ScopedSetLogSettings::~ScopedSetLogSettings().

23  {
24  // Validate the new settings as we set them.
26  std::min(LOG_FATAL, settings.min_log_level);
27 }
LogSettings g_log_settings
LogSeverity min_log_level
Definition: log_settings.h:25
constexpr LogSeverity LOG_FATAL
Definition: log_level.h:16

◆ ShouldCreateLogMessage()

bool fml::ShouldCreateLogMessage ( LogSeverity  severity)

Definition at line 104 of file logging.cc.

References GetMinLogLevel().

Referenced by fml::LogMessage::stream().

104  {
105  return severity >= GetMinLogLevel();
106 }
int GetMinLogLevel()
Definition: log_settings.cc:33

◆ SignalHandler()

static void fml::SignalHandler ( int  signal)
static

Definition at line 108 of file backtrace.cc.

References BacktraceHere(), FML_LOG, SignalNameToString(), and ToggleSignalHandlers().

Referenced by ToggleSignalHandlers().

108  {
109  // We are a crash signal handler. This can only happen once. Since we don't
110  // want to catch crashes while we are generating the crash reports, disable
111  // all set signal handlers to their default values before reporting the crash
112  // and re-raising the signal.
113  ToggleSignalHandlers(false);
114 
115  FML_LOG(ERROR) << "Caught signal " << SignalNameToString(signal)
116  << " during program execution." << std::endl
117  << BacktraceHere(3);
118 
119  ::raise(signal);
120 }
std::string BacktraceHere(size_t offset)
Definition: backtrace.cc:57
#define FML_LOG(severity)
Definition: logging.h:65
static void ToggleSignalHandlers(bool set)
Definition: backtrace.cc:122
static std::string SignalNameToString(int signal)
Definition: backtrace.cc:84

◆ SignalNameToString()

static std::string fml::SignalNameToString ( int  signal)
static

Definition at line 84 of file backtrace.cc.

References ToggleSignalHandlers().

Referenced by SignalHandler().

84  {
85  switch (signal) {
86  case SIGABRT:
87  return "SIGABRT";
88  case SIGFPE:
89  return "SIGFPE";
90  case SIGBUS:
91  return "SIGBUS";
92  case SIGSEGV:
93  return "SIGSEGV";
94  case SIGSYS:
95  return "SIGSYS";
96  case SIGPIPE:
97  return "SIGPIPE";
98  case SIGALRM:
99  return "SIGALRM";
100  case SIGTERM:
101  return "SIGTERM";
102  };
103  return std::to_string(signal);
104 }

◆ size()

template<typename T , std::size_t N>
constexpr std::size_t fml::size ( T(&)  array[N])

Definition at line 13 of file size.h.

Referenced by flutter::GPUSurfaceSoftware::AcquireFrame(), flutter_runner::VulkanSurfacePool::AcquireSurface(), CommandLineToArgv(), GoldenImage::compareGoldenToImage:, flutter::SceneUpdateContext::CompositeEmbeddedView(), flutter::Rasterizer::compositor_context(), fml::Message::Decode(), flutter::MessageCodec< rapidjson::Document >::DecodeMessage(), flutter::MethodCodec< rapidjson::Document >::DecodeMethodCall(), DefaultSettingsForProcess(), flutter_runner_test::MockSemanticsManager::DeleteSemanticNodes(), flutter::Rasterizer::Draw(), flutter::EmbedderSurfaceSoftware::EmbedderSurfaceSoftware(), FlutterEngineInitialize(), FlutterPlatformMessageCreateResponseHandle(), FlutterSizeMake(), tonic::DartConverter< DartConverterMapping >::FromDart(), flutter::MergedContainerLayer::GetChildContainer(), flutter::testing::GetDebuggerStatus(), GetFileAttributesForUtf8Path(), GetLastErrorMessage(), flutter::FlutterMain::GetSettings(), vulkan::VulkanSwapchain::GetSize(), flutter_runner::VulkanSurface::GetSize(), fml::Message::GetSizeRead(), vulkan::VulkanDevice::GetSurfaceCapabilities(), flutter::GetSymbolMapping(), flutter::DartVM::GetVMLaunchCount(), flutter::Engine::HintFreed(), flutter::Win32Window::InitializeChild(), flutter::IOSExternalTextureGL::IOSExternalTextureGL(), flutter::IsAllowedDartVMFlag(), flutter_runner::VulkanSurfaceProducer::IsValid(), android::JenkinsHashMix(), fml::paths::JoinPaths(), tonic::Log(), flutter::PlatformViewAndroid::NotifyChanged(), flutter::ParseLanguageName(), PopulateSnapshotMappingCallbacks(), flutter::StandardCodecSerializer::ReadValueOfType(), flutter::SomeDataExtensionSerializer::ReadValueOfType(), FlutterStandardReader::readValueOfType:, flutter::VsyncWaiterAndroid::Register(), flutter::FlutterMain::Register(), flutter::RegisterApi(), flutter::testing::ResetAssetManager(), flutter::SaveCompilationTrace(), flutter::testing::EmbedderTestContextGL::SetGLPresentCallback(), flutter::testing::ShellTestPlatformViewVulkan::SimulateVSync(), zircon::dart::System::SocketRead(), flutter_runner::VulkanSurfacePool::SubmitSurface(), flutter_runner::FuchsiaExternalViewEmbedder::SupportsDynamicThreadMerging(), flutter_runner::Surface::Surface(), filesystem::TEST(), flutter::testing::TEST(), flutter::TEST(), flutter::testing::TEST_F(), TimerDrain(), TruncateFile(), flutter_runner_test::MockSemanticsManager::UpdateSemanticNodes(), flutter::SceneUpdateContext::UpdateView(), flutter::VectorToSize(), zircon::dart::System::VmoGetSize(), zircon::dart::System::VmoMap(), zircon::dart::System::VmoRead(), zircon::dart::System::VmoSetSize(), flutter::WrapOnscreenSurface(), flutter::StandardCodecSerializer::WriteSize(), FlutterStandardWriter::writeSize:, flutter::StandardCodecSerializer::WriteValue(), and minikin::WordBreaker::~WordBreaker().

13  {
14  return N;
15 }

◆ strdup()

char * fml::strdup ( const char *  str1)

◆ StringToWideString()

std::wstring fml::StringToWideString ( const std::string &  str)
inline

Definition at line 17 of file wstring_conversion.h.

Referenced by GetFileAttributesForUtf8Path().

17  {
18  WideStringConvertor converter;
19  return converter.from_bytes(str);
20 }
std::wstring_convert< std::codecvt_utf8_utf16< wchar_t >, wchar_t > WideStringConvertor

◆ swap() [1/2]

◆ swap() [2/2]

template<class T , class Traits >
void fml::swap ( const UniqueObject< T, Traits > &  a,
const UniqueObject< T, Traits > &  b 
)

Definition at line 121 of file unique_object.h.

References fml::UniqueObject< T, Traits >::swap().

Referenced by fml::UniqueObject< fdio_ns_t *, UniqueFDIONSTraits >::swap().

121  {
122  a.swap(b);
123 }

◆ TEST() [1/4]

fml::TEST ( CountDownLatchTest  ,
CanWaitOnZero   
)

Definition at line 16 of file count_down_latch_unittests.cc.

References fml::CountDownLatch::Wait().

16  {
17  CountDownLatch latch(0);
18  latch.Wait();
19 }

◆ TEST() [2/4]

fml::TEST ( MessageTest  ,
CanEncodeTriviallyCopyableTypes   
)

Definition at line 17 of file message_unittests.cc.

References fml::Message::Encode(), fml::Message::GetBufferSize(), fml::Message::GetDataLength(), and fml::Message::GetSizeRead().

17  {
18  Message message;
19  ASSERT_TRUE(message.Encode(12));
20  ASSERT_TRUE(message.Encode(11.0f));
21  ASSERT_TRUE(message.Encode('a'));
22 
23  TestStruct s;
24  ASSERT_TRUE(message.Encode(s));
25  ASSERT_GE(message.GetDataLength(), 0u);
26  ASSERT_GE(message.GetBufferSize(), 0u);
27  ASSERT_EQ(message.GetSizeRead(), 0u);
28 }

◆ TEST() [3/4]

fml::TEST ( CountDownLatchTest  ,
CanWait   
)

Definition at line 26 of file count_down_latch_unittests.cc.

References fml::CountDownLatch::CountDown(), fml::Thread::GetTaskRunner(), and fml::CountDownLatch::Wait().

26  {
27  fml::Thread thread("test_thread");
28  const size_t count = 100;
29  size_t current_count = 0;
30  CountDownLatch latch(count);
31  auto decrement_latch_on_thread = [runner = thread.GetTaskRunner(), &latch,
32  &current_count]() {
33  runner->PostTask([&latch, &current_count]() {
34  std::this_thread::sleep_for(std::chrono::microseconds(100));
35  current_count++;
36  latch.CountDown();
37  });
38  };
39  for (size_t i = 0; i < count; ++i) {
40  decrement_latch_on_thread();
41  }
42  latch.Wait();
43  ASSERT_EQ(current_count, count);
44 }

◆ TEST() [4/4]

fml::TEST ( MessageTest  ,
CanDecodeTriviallyCopyableTypes   
)

Definition at line 30 of file message_unittests.cc.

References fml::TestStruct::a, fml::TestStruct::b, fml::TestStruct::c, fml::Message::Decode(), fml::Message::Encode(), fml::Message::GetBufferSize(), fml::Message::GetDataLength(), and fml::Message::GetSizeRead().

30  {
31  Message message;
32  ASSERT_TRUE(message.Encode(12));
33  ASSERT_TRUE(message.Encode(11.0f));
34  ASSERT_TRUE(message.Encode('a'));
35  TestStruct s;
36  s.a = 10;
37  s.b = 'y';
38  s.c = 11.1f;
39 
40  ASSERT_TRUE(message.Encode(s));
41 
42  ASSERT_GE(message.GetDataLength(), 0u);
43  ASSERT_GE(message.GetBufferSize(), 0u);
44  ASSERT_EQ(message.GetSizeRead(), 0u);
45 
46  int int1 = 0;
47  ASSERT_TRUE(message.Decode(int1));
48  ASSERT_EQ(12, int1);
49 
50  float float1 = 0.0f;
51  ASSERT_TRUE(message.Decode(float1));
52  ASSERT_EQ(float1, 11.0f);
53 
54  char char1 = 'x';
55  ASSERT_TRUE(message.Decode(char1));
56  ASSERT_EQ(char1, 'a');
57 
58  TestStruct s1;
59  ASSERT_TRUE(message.Decode(s1));
60  ASSERT_EQ(s1.a, 10);
61  ASSERT_EQ(s1.b, 'y');
62  ASSERT_EQ(s1.c, 11.1f);
63 
64  ASSERT_NE(message.GetSizeRead(), 0u);
65  ASSERT_EQ(message.GetDataLength(), message.GetSizeRead());
66 }

◆ TimerDrain()

bool fml::TimerDrain ( int  fd)

Drains the timer FD and returns true if it has expired. This may be false in case the timer read is non-blocking and this routine was called before the timer expiry.

Definition at line 54 of file timerfd.cc.

References FML_HANDLE_EINTR, and size().

Referenced by AcquireLooperForThread().

54  {
55  // 8 bytes must be read from a signaled timer file descriptor when signaled.
56  uint64_t fire_count = 0;
57  ssize_t size = FML_HANDLE_EINTR(::read(fd, &fire_count, sizeof(uint64_t)));
58  if (size != sizeof(uint64_t)) {
59  return false;
60  }
61  return fire_count > 0;
62 }
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
#define FML_HANDLE_EINTR(x)
Definition: eintr_wrapper.h:33

◆ TimerRearm()

bool fml::TimerRearm ( int  fd,
fml::TimePoint  time_point 
)

Rearms the timer to expire at the given time point.

Definition at line 36 of file timerfd.cc.

References NSEC_PER_SEC, TFD_TIMER_ABSTIME, timerfd_settime(), fml::TimePoint::ToEpochDelta(), and fml::TimeDelta::ToNanoseconds().

Referenced by AcquireLooperForThread().

36  {
37  uint64_t nano_secs = time_point.ToEpochDelta().ToNanoseconds();
38 
39  // "0" will disarm the timer, desired behavior is to immediately
40  // trigger the timer.
41  if (nano_secs < 1) {
42  nano_secs = 1;
43  }
44 
45  struct itimerspec spec = {};
46  spec.it_value.tv_sec = (time_t)(nano_secs / NSEC_PER_SEC);
47  spec.it_value.tv_nsec = nano_secs % NSEC_PER_SEC;
48  spec.it_interval = spec.it_value; // single expiry.
49 
50  int result = ::timerfd_settime(fd, TFD_TIMER_ABSTIME, &spec, nullptr);
51  return result == 0;
52 }
int timerfd_settime(int ufc, int flags, const struct itimerspec *utmr, struct itimerspec *otmr)
Definition: timerfd.cc:21
#define NSEC_PER_SEC
Definition: timerfd.cc:33
TimeDelta ToEpochDelta() const
Definition: time_point.h:40
constexpr int64_t ToNanoseconds() const
Definition: time_delta.h:61
#define TFD_TIMER_ABSTIME
Definition: timerfd.h:29

◆ ToggleSignalHandlers()

static void fml::ToggleSignalHandlers ( bool  set)
static

Definition at line 122 of file backtrace.cc.

References FML_LOG, kKnownSignalHandlers, and SignalHandler().

Referenced by InstallCrashHandler(), SignalHandler(), and SignalNameToString().

122  {
123  for (size_t i = 0; i < sizeof(kKnownSignalHandlers) / sizeof(size_t); ++i) {
124  auto signal_name = kKnownSignalHandlers[i];
125  auto handler = set ? &SignalHandler : SIG_DFL;
126 
127  if (::signal(signal_name, handler) == SIG_ERR) {
128  FML_LOG(ERROR) << "Could not attach signal handler for " << signal_name;
129  }
130  }
131 }
#define FML_LOG(severity)
Definition: logging.h:65
static void SignalHandler(int signal)
Definition: backtrace.cc:108
static size_t kKnownSignalHandlers[]
Definition: backtrace.cc:73

◆ ToPosixAccessFlags()

static int fml::ToPosixAccessFlags ( FilePermission  permission)
static

Definition at line 32 of file file_posix.cc.

References flutter::flags, kRead, kReadWrite, and kWrite.

Referenced by OpenFile().

32  {
33  int flags = 0;
34  switch (permission) {
35  case FilePermission::kRead:
36  flags |= O_RDONLY; // read only
37  break;
38  case FilePermission::kWrite:
39  flags |= O_WRONLY; // write only
40  break;
41  case FilePermission::kReadWrite:
42  flags |= O_RDWR; // read-write
43  break;
44  }
45  return flags;
46 }
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66

◆ ToPosixCreateModeFlags()

static int fml::ToPosixCreateModeFlags ( FilePermission  permission)
static

Definition at line 48 of file file_posix.cc.

References kRead, kReadWrite, and kWrite.

Referenced by OpenDirectory(), and OpenFile().

48  {
49  int mode = 0;
50  switch (permission) {
51  case FilePermission::kRead:
52  mode |= S_IRUSR;
53  break;
54  case FilePermission::kWrite:
55  mode |= S_IWUSR;
56  break;
57  case FilePermission::kReadWrite:
58  mode |= S_IRUSR | S_IWUSR;
59  break;
60  }
61  return mode;
62 }

◆ ToPosixProtectionFlags()

static int fml::ToPosixProtectionFlags ( std::initializer_list< FileMapping::Protection protection_flags)
static

Definition at line 20 of file mapping_posix.cc.

References flutter::flags, fml::FileMapping::kExecute, fml::FileMapping::kRead, and fml::FileMapping::kWrite.

21  {
22  int flags = 0;
23  for (auto protection : protection_flags) {
24  switch (protection) {
25  case FileMapping::Protection::kRead:
26  flags |= PROT_READ;
27  break;
28  case FileMapping::Protection::kWrite:
29  flags |= PROT_WRITE;
30  break;
31  case FileMapping::Protection::kExecute:
32  flags |= PROT_READ | PROT_EXEC;
33  break;
34  }
35  }
36  return flags;
37 }
DEF_SWITCHES_START snapshot asset Path to the directory containing the four files specified by VmSnapshotInstructions and IsolateSnapshotInstructions vm snapshot The VM instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present isolate snapshot The isolate instructions snapshot that will be memory mapped as read and executable SnapshotAssetPath must be present icu symbol Prefix for the symbols representing ICU data linked into the Flutter library dart flags
Definition: switches.h:66

◆ TruncateFile()

bool fml::TruncateFile ( const fml::UniqueFD file,
size_t  size 
)

Definition at line 152 of file file_posix.cc.

References fml::UniqueObject< T, Traits >::get(), fml::UniqueObject< T, Traits >::is_valid(), and size().

Referenced by GetFileAttributesForUtf8Path(), TEST(), WriteAtomically(), and WriteStringToFile().

152  {
153  if (!file.is_valid()) {
154  return false;
155  }
156 
157  return ::ftruncate(file.get(), size) == 0;
158 }
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
const T & get() const
Definition: unique_object.h:87
bool is_valid() const
Definition: unique_object.h:89

◆ UnlinkDirectory() [1/2]

bool fml::UnlinkDirectory ( const char *  path)

◆ UnlinkDirectory() [2/2]

bool fml::UnlinkDirectory ( const fml::UniqueFD base_directory,
const char *  path 
)

Definition at line 164 of file file_posix.cc.

References fml::UniqueObject< T, Traits >::get(), and flutter::path.

164  {
165  return ::unlinkat(base_directory.get(), path, AT_REMOVEDIR) == 0;
166 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
const T & get() const
Definition: unique_object.h:87

◆ UnlinkFile() [1/2]

bool fml::UnlinkFile ( const char *  path)

Definition at line 168 of file file_posix.cc.

References flutter::path.

Referenced by GetFileAttributesForUtf8Path(), flutter::PersistentCache::Purge(), RemoveFilesInDirectory(), TEST(), and flutter::testing::TEST_F().

168  {
169  return UnlinkFile(fml::UniqueFD{AT_FDCWD}, path);
170 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
bool UnlinkFile(const char *path)
Definition: file_posix.cc:168

◆ UnlinkFile() [2/2]

bool fml::UnlinkFile ( const fml::UniqueFD base_directory,
const char *  path 
)

Definition at line 172 of file file_posix.cc.

References FML_DLOG, fml::UniqueObject< T, Traits >::get(), and flutter::path.

172  {
173  int code = ::unlinkat(base_directory.get(), path, 0);
174  if (code != 0) {
175  FML_DLOG(ERROR) << strerror(errno);
176  }
177  return code == 0;
178 }
DEF_SWITCHES_START snapshot asset path
Definition: switches.h:32
const T & get() const
Definition: unique_object.h:87
#define FML_DLOG(severity)
Definition: logging.h:85

◆ VisitFiles()

bool fml::VisitFiles ( const fml::UniqueFD directory,
const FileVisitor visitor 
)

Call visitor on all files inside the directory non-recursively. The trivial file "." and ".." will not be visited.

Return false if and only if the visitor returns false during the traversal.

If recursive visiting is needed, call VisitFiles inside the visitor, or use our helper method VisitFilesRecursively.

See also
VisitFilesRecursively.
Note
Procedure doesn't copy all closures.

Definition at line 233 of file file_posix.cc.

References FML_DLOG, fml::UniqueObject< T, Traits >::get(), fml::UniqueObject< T, Traits >::is_valid(), and fml::UniqueObject< T, Traits >::release().

Referenced by GetFileAttributesForUtf8Path(), flutter::PersistentCache::LoadSkSLs(), flutter::PersistentCache::Purge(), RemoveFilesInDirectory(), TEST(), flutter::testing::TEST_F(), and VisitFilesRecursively().

233  {
234  fml::UniqueFD dup_fd(dup(directory.get()));
235  if (!dup_fd.is_valid()) {
236  FML_DLOG(ERROR) << "Can't dup the directory fd. Error: " << strerror(errno);
237  return true; // continue to visit other files
238  }
239 
240  fml::UniqueDir dir(::fdopendir(dup_fd.get()));
241  if (!dir.is_valid()) {
242  FML_DLOG(ERROR) << "Can't open the directory. Error: " << strerror(errno);
243  return true; // continue to visit other files
244  }
245 
246  // The directory fd will be closed by `closedir`.
247  (void)dup_fd.release();
248 
249  // Without `rewinddir`, `readir` will directly return NULL (end of dir is
250  // reached) after a previuos `VisitFiles` call for the same `const
251  // fml::UniqueFd& directory`.
252  rewinddir(dir.get());
253  while (dirent* ent = readdir(dir.get())) {
254  std::string filename = ent->d_name;
255  if (filename != "." && filename != "..") {
256  if (!visitor(directory, filename)) {
257  return false;
258  }
259  }
260  }
261 
262  return true;
263 }
const T & get() const
Definition: unique_object.h:87
#define FML_DLOG(severity)
Definition: logging.h:85

◆ VisitFilesRecursively()

bool fml::VisitFilesRecursively ( const fml::UniqueFD directory,
const FileVisitor visitor 
)

Recursively call visitor on all files inside the directory. Return false if and only if the visitor returns false during the traversal.

This is a helper method that wraps the general VisitFiles method. The VisitFiles is strictly more powerful as it has the access of the recursion stack to the file. For example, VisitFiles may be able to maintain a vector of directory names that lead to a file. That could be useful to compute the relative path between the root directory and the visited file.

See also
VisitFiles.
Note
Procedure doesn't copy all closures.

Definition at line 71 of file file.cc.

References FML_LOG, fml::UniqueObject< T, Traits >::is_valid(), IsDirectory(), OpenDirectoryReadOnly(), and VisitFiles().

Referenced by flutter::PersistentCache::Purge(), TEST(), and flutter::testing::TEST_F().

72  {
73  FileVisitor recursive_visitor = [&recursive_visitor, &visitor](
74  const UniqueFD& directory,
75  const std::string& filename) {
76  if (!visitor(directory, filename)) {
77  return false;
78  }
79  if (IsDirectory(directory, filename.c_str())) {
80  UniqueFD sub_dir = OpenDirectoryReadOnly(directory, filename.c_str());
81  if (!sub_dir.is_valid()) {
82  FML_LOG(ERROR) << "Can't open sub-directory: " << filename;
83  return true;
84  }
85  return VisitFiles(sub_dir, recursive_visitor);
86  }
87  return true;
88  };
89  return VisitFiles(directory, recursive_visitor);
90 }
std::function< bool(const fml::UniqueFD &directory, const std::string &filename)> FileVisitor
Definition: file.h:98
UniqueObject< int, internal::os_unix::UniqueFDTraits > UniqueFD
Definition: unique_fd.h:61
#define FML_LOG(severity)
Definition: logging.h:65
bool VisitFiles(const fml::UniqueFD &directory, const FileVisitor &visitor)
Definition: file_posix.cc:233
bool IsDirectory(const fml::UniqueFD &directory)
Definition: file_posix.cc:124
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition: file.cc:97

◆ WaitWithTimeoutImpl()

template<typename ConditionFn >
bool fml::WaitWithTimeoutImpl ( std::unique_lock< std::mutex > *  locker,
std::condition_variable *  cv,
ConditionFn  condition,
TimeDelta  timeout 
)

Definition at line 20 of file waitable_event.cc.

References FML_DCHECK, fml::TimePoint::Now(), and fml::TimeDelta::ToNanoseconds().

Referenced by fml::ManualResetWaitableEvent::WaitWithTimeout().

23  {
24  FML_DCHECK(locker->owns_lock());
25 
26  if (condition()) {
27  return false;
28  }
29 
30  // We may get spurious wakeups.
31  TimeDelta wait_remaining = timeout;
32  TimePoint start = TimePoint::Now();
33  while (true) {
34  if (std::cv_status::timeout ==
35  cv->wait_for(*locker, std::chrono::nanoseconds(
36  wait_remaining.ToNanoseconds()))) {
37  return true; // Definitely timed out.
38  }
39 
40  // We may have been awoken.
41  if (condition()) {
42  return false;
43  }
44 
45  // Or the wakeup may have been spurious.
46  TimePoint now = TimePoint::Now();
47  FML_DCHECK(now >= start);
48  TimeDelta elapsed = now - start;
49  // It's possible that we may have timed out anyway.
50  if (elapsed >= timeout) {
51  return true;
52  }
53 
54  // Otherwise, recalculate the amount that we have left to wait.
55  wait_remaining = timeout - elapsed;
56  }
57 }
#define FML_DCHECK(condition)
Definition: logging.h:86

◆ WideStringToString()

std::string fml::WideStringToString ( const std::wstring &  wstr)
inline

Definition at line 22 of file wstring_conversion.h.

Referenced by GetFileAttributesForUtf8Path(), GetFullHandlePath(), and GetLastErrorMessage().

22  {
23  WideStringConvertor converter;
24  return converter.to_bytes(wstr);
25 }
std::wstring_convert< std::codecvt_utf8_utf16< wchar_t >, wchar_t > WideStringConvertor

◆ WriteAtomically()

bool fml::WriteAtomically ( const fml::UniqueFD base_directory,
const char *  file_name,
const Mapping mapping 
)

Definition at line 188 of file file_posix.cc.

References FML_HANDLE_EINTR, fml::UniqueObject< T, Traits >::get(), fml::Mapping::GetMapping(), fml::Mapping::GetSize(), kReadWrite, OpenFile(), and TruncateFile().

Referenced by GetFileAttributesForUtf8Path(), flutter::PersistentCacheStore(), TEST(), flutter::testing::TEST_F(), and flutter::testing::WriteImageToDisk().

190  {
191  if (file_name == nullptr || data.GetMapping() == nullptr) {
192  return false;
193  }
194 
195  std::stringstream stream;
196  stream << file_name << ".temp";
197  const auto temp_file_name = stream.str();
198 
199  auto temp_file = OpenFile(base_directory, temp_file_name.c_str(), true,
200  FilePermission::kReadWrite);
201  if (!temp_file.is_valid()) {
202  return false;
203  }
204 
205  if (!TruncateFile(temp_file, data.GetSize())) {
206  return false;
207  }
208 
209  ssize_t remaining = data.GetSize();
210  ssize_t written = 0;
211  ssize_t offset = 0;
212 
213  while (remaining > 0) {
214  written = FML_HANDLE_EINTR(
215  ::write(temp_file.get(), data.GetMapping() + offset, remaining));
216 
217  if (written == -1) {
218  return false;
219  }
220 
221  remaining -= written;
222  offset += written;
223  }
224 
225  if (::fsync(temp_file.get()) != 0) {
226  return false;
227  }
228 
229  return ::renameat(base_directory.get(), temp_file_name.c_str(),
230  base_directory.get(), file_name) == 0;
231 }
const T & get() const
Definition: unique_object.h:87
#define FML_HANDLE_EINTR(x)
Definition: eintr_wrapper.h:33
fml::UniqueFD OpenFile(const char *path, bool create_if_necessary, FilePermission permission)
This can open a directory on POSIX, but not on Windows.
Definition: file_posix.cc:64
bool TruncateFile(const fml::UniqueFD &file, size_t size)
Definition: file_posix.cc:152

Variable Documentation

◆ _kUnmerged

◆ kClockType [1/2]

constexpr int fml::kClockType = CLOCK_MONOTONIC
static

Definition at line 14 of file message_loop_android.cc.

◆ kClockType [2/2]

constexpr int fml::kClockType = CLOCK_MONOTONIC
static

Definition at line 15 of file message_loop_linux.cc.

◆ kDecodeMap

constexpr signed char fml::kDecodeMap[]
static
Initial value:
= {
26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}

Definition at line 45 of file base32.cc.

◆ kDecodeMapSize

constexpr int fml::kDecodeMapSize
static
Initial value:
=
sizeof(kDecodeMap) / sizeof(kDecodeMap[0])
static constexpr signed char kDecodeMap[]
Definition: base32.cc:45

Definition at line 51 of file base32.cc.

◆ kDefaultFrameBudget

constexpr Milliseconds fml::kDefaultFrameBudget = Milliseconds(1s) / 60

◆ kDistantFuture

constexpr CFTimeInterval fml::kDistantFuture = 1.0e10
static

Definition at line 14 of file message_loop_darwin.mm.

◆ kEncoding

constexpr char fml::kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
static

Definition at line 12 of file base32.cc.

◆ kKnownSignalHandlers

size_t fml::kKnownSignalHandlers[]
static
Initial value:
= {
SIGABRT,
SIGFPE,
SIGBUS,
SIGSEGV,
SIGSYS,
SIGPIPE,
SIGALRM,
SIGTERM,
}

Definition at line 73 of file backtrace.cc.

Referenced by ToggleSignalHandlers().

◆ kKUnknownFrameName [1/2]

std::string fml::kKUnknownFrameName = "Unknown"
static

Definition at line 9 of file backtrace_stub.cc.

◆ kKUnknownFrameName [2/2]

std::string fml::kKUnknownFrameName = "Unknown"
static

Definition at line 23 of file backtrace.cc.

Referenced by DemangleSymbolName(), and GetSymbolName().

◆ LOG_DFATAL

const LogSeverity fml::LOG_DFATAL = LOG_FATAL

Definition at line 30 of file log_level.h.

◆ LOG_ERROR

constexpr LogSeverity fml::LOG_ERROR = 2

◆ LOG_FATAL

constexpr LogSeverity fml::LOG_FATAL = 3

Definition at line 16 of file log_level.h.

Referenced by GetMinLogLevel(), SetLogSettings(), and fml::LogMessage::~LogMessage().

◆ LOG_INFO

◆ LOG_NUM_SEVERITIES

constexpr LogSeverity fml::LOG_NUM_SEVERITIES = 4

Definition at line 17 of file log_level.h.

◆ LOG_WARNING

constexpr LogSeverity fml::LOG_WARNING = 1

Definition at line 14 of file log_level.h.

Referenced by flutter::testing::TEST_F(), and fml::LogMessage::~LogMessage().

◆ tls_message_loop

Definition at line 17 of file message_loop.cc.