Ark Server API (ASA) - Wiki
Loading...
Searching...
No Matches
GenericPlatformProcess.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#include "Containers/Array.h"
6#include "Containers/UnrealString.h"
7#include "CoreTypes.h"
8#include "GenericPlatform/GenericPlatformAffinity.h"
9#include "HAL/PlatformCrt.h"
10#include "HAL/PlatformMisc.h"
11#include "Misc/EnumClassFlags.h"
12#include "Templates/Function.h"
13
14class FEvent;
15
16////////////////////////////////////////////////////////////////////////////////
18#include <immintrin.h>
19#endif
20
21////////////////////////////////////////////////////////////////////////////////
23#include <mach/mach_time.h>
24#endif
25
26////////////////////////////////////////////////////////////////////////////////
27#if !defined(__clang__)
28# include <intrin.h>
29# if defined(_M_ARM)
30# include <armintr.h>
31# elif defined(_M_ARM64)
32# include <arm64intr.h>
33# endif
34#endif
35
36class Error;
37struct FProcHandle;
38template <typename FuncType> class TFunctionRef;
39
40namespace EProcessResource
41{
42 enum Type
43 {
44 /**
45 * Limits address space - basically limits the largest address the process can get. Affects mmap() (won't be able to map files larger than that) among others.
46 * May also limit automatic stack expansion, depending on platform (e.g. Linux)
47 */
49 };
50}
51
52
53/** Not all platforms have different opening semantics, but Windows allows you to specify a specific verb when opening a file. */
54namespace ELaunchVerb
55{
56 enum Type
57 {
58 /** Launch the application associated with opening file to 'view' */
59 Open,
60
61 /** Launch the application associated with opening file to 'edit' */
62 Edit,
63 };
64}
65
66/** Forward declaration for ENamedThreads */
68{
69 enum Type : int32;
70}
71
72namespace UE::Core
73{
75}
76
77/** Generic implementation for the process handle. */
78template< typename T, T InvalidHandleValue >
80{
81 typedef T HandleType;
82public:
83
84 /** Default constructor. */
87 { }
88
89 /** Initialization constructor. */
90 FORCEINLINE explicit TProcHandle( T Other )
91 : Handle( Other )
92 { }
93
94 /** Assignment operator. */
96 {
97 if( this != &Other )
98 {
100 }
101 return *this;
102 }
103
104 /** Accessors. */
105 FORCEINLINE T Get() const
106 {
107 return Handle;
108 }
109
111 {
113 }
114
115 FORCEINLINE bool IsValid() const
116 {
117 return Handle != InvalidHandleValue;
118 }
119
120protected:
121 /** Platform specific handle. */
123};
124
125
126struct FProcHandle;
127
128/**
129* Generic implementation for most platforms, these tend to be unused and unimplemented
130**/
132{
133 /**
134 * Generic representation of a interprocess semaphore
135 */
137 {
138 /** Returns the name of the object */
139 const TCHAR* GetName() const
140 {
141 return Name;
142 }
143
144 /** Acquires an exclusive access (also known as Wait()) */
145 virtual void Lock() = 0;
146
147 /**
148 * Tries to acquire and exclusive access for a specified amount of nanoseconds (also known as TryWait()).
149 *
150 * @param Nanoseconds (10^-9 seconds) to wait for,
151 * @return false if was not able to lock within given time
152 */
153 virtual bool TryLock(uint64 NanosecondsToWait) = 0;
154
155 /** Relinquishes an exclusive access (also known as Release())*/
156 virtual void Unlock() = 0;
157
158 /**
159 * Creates and initializes a new instance with the specified name.
160 *
161 * @param InName name of the semaphore (all processes should use the same)
162 */
163 FSemaphore(const FString& InName);
164
165 /**
166 * Creates and initializes a new instance with the specified name.
167 *
168 * @param InName name of the semaphore (all processes should use the same)
169 */
170 FSemaphore(const TCHAR* InName);
171
172 /** Virtual destructor. */
173 virtual ~FSemaphore() { };
174
175 protected:
176
178 {
179 MaxSemaphoreName = 128
180 };
181
182 /** Name of the region */
184 };
185
186 /** Load a DLL. **/
187 static void* GetDllHandle( const TCHAR* Filename );
188
189 /** Free a DLL. **/
190 static void FreeDllHandle( void* DllHandle );
191
192 /** Lookup the address of a DLL function. **/
193 static void* GetDllExport( void* DllHandle, const TCHAR* ProcName );
194
195 /** Adds a directory to search in when resolving implicitly loaded or filename-only DLLs. **/
196 FORCEINLINE static void AddDllDirectory(const TCHAR* Directory)
197 {
198
199 }
200
201 /** Set a directory to look for DLL files. NEEDS to have a Pop call when complete */
202 FORCEINLINE static void PushDllDirectory(const TCHAR* Directory)
203 {
204
205 }
206
207 /** Unsets a directory to look for DLL files. The same directory must be passed in as the Push call to validate */
208 FORCEINLINE static void PopDllDirectory(const TCHAR* Directory)
209 {
210
211 }
212
213 /** Get the list of registered directories to search in when resolving implicitly loaded or filename-only DLLs. **/
214 FORCEINLINE static void GetDllDirectories(TArray<FString>& OutDllDirectories)
215 {
216
217 }
218
219 /**
220 * Retrieves the ProcessId of this process.
221 *
222 * @return the ProcessId of this process.
223 */
224 static uint32 GetCurrentProcessId();
225
226 /**
227 * Retrieves the current hardware CPU core
228 *
229 * @return the current hardware core.
230 */
231 static uint32 GetCurrentCoreNumber();
232
233 /**
234 * Change the thread processor affinity
235 *
236 * @param AffinityMask A bitfield indicating what processors the thread is allowed to run on.
237 */
238 static void SetThreadAffinityMask( uint64 AffinityMask );
239
240 /**
241 * Change the thread processor priority
242 *
243 * @param NewPriority an EThreadPriority indicating what priority the thread is to run at.
244 */
245 static void SetThreadPriority( EThreadPriority NewPriority );
246
247 /**
248 * Helper function to set thread name of the current thread.
249 * @param ThreadName Name to set
250 */
251 static void SetThreadName( const TCHAR* ThreadName ) { }
252
253 /** Get the active stack size for the currently running thread **/
254 static uint32 GetStackSize();
255
256 /** Output information about the currently active thread **/
257 static void DumpThreadInfo( const TCHAR* MarkerName ) { }
258
259 /** Allow the platform to do anything it needs for game thread */
260 static void SetupGameThread() { }
261
262 /** Allow the platform to do anything it needs for render thread */
263 static void SetupRenderThread() { }
264
265 /** Allow the platform to do anything it needs for the RHI thread */
266 static void SetupRHIThread() { }
267
268 /** Allow the platform to do anything it needs for audio thread */
269 static void SetupAudioThread() { }
270
271 /** Allow the platform to tear down the audio thread */
272 static void TeardownAudioThread() { }
273
274 /** Content saved to the game or engine directories should be rerouted to user directories instead **/
275 static bool ShouldSaveToUserDir();
276
277 /** Get startup directory. NOTE: Only one return value is valid at a time! **/
278 static const TCHAR* BaseDir();
279
280 /** Get user directory. NOTE: Only one return value is valid at a time! **/
281 static const TCHAR* UserDir();
282
283 /** Get the user settings directory. NOTE: Only one return value is valid at a time! **/
284 static const TCHAR *UserSettingsDir();
285
286 /** Get the user temporary directory. NOTE: Only one return value is valid at a time! **/
287 static const TCHAR *UserTempDir();
288
289 /** Get the user home directory. NOTE: Only one return value is valid at a time! **/
290 static const TCHAR *UserHomeDir();
291
292 /** Get application settings directory. NOTE: Only one return value is valid at a time! **/
293 static const TCHAR* ApplicationSettingsDir();
294
295 /** Get computer name. NOTE: Only one return value is valid at a time! **/
296 static const TCHAR* ComputerName();
297
298 /** Get user name. NOTE: Only one return value is valid at a time! **/
299 static const TCHAR* UserName(bool bOnlyAlphaNumeric = true);
300 static const TCHAR* ShaderDir();
301 static void SetShaderDir(const TCHAR*Where);
303
304 /** Get the current working directory (only really makes sense on desktop platforms) */
306
307 /**
308 * Sets the process limits.
309 *
310 * @param Resource one of process resources.
311 * @param Limit the maximum amount of the resource (for some OS, this means both hard and soft limits).
312 * @return true on success, false otherwise.
313 */
314 static bool SetProcessLimits(EProcessResource::Type Resource, uint64 Limit)
315 {
316 return true; // return fake success by default, that way the game won't early quit on platforms that don't implement this
317 }
318
319 /**
320 * Get the shader working directory.
321 *
322 * @return The path to the directory.
323 */
324 static const FString ShaderWorkingDir();
325
326 /** Clean the shader working directory. */
328
329 /**
330 * Return the path to the currently running executable
331 *
332 * @return Path of the currently running executable
333 */
334 static const TCHAR* ExecutablePath();
335
336 /**
337 * Return the name of the currently running executable
338 *
339 * @param bRemoveExtension true to remove the extension of the executable name, false to leave it intact
340 * @return Name of the currently running executable
341 */
342 static const TCHAR* ExecutableName(bool bRemoveExtension = true);
343
344 /**
345 * Generates the path to the specified application or game.
346 *
347 * The application must reside in the Engine's binaries directory. The returned path is relative to this
348 * executable's directory.For example, calling this method with "UE4" and EBuildConfiguration::Debug
349 * on Windows 64-bit will generate the path "../Win64/UnrealEditor-Win64-Debug.exe"
350 *
351 * @param AppName The name of the application or game.
352 * @param BuildConfiguration The build configuration of the game.
353 * @return The generated application path.
354 */
355 static FString GenerateApplicationPath( const FString& AppName, EBuildConfiguration BuildConfiguration);
356
357 /**
358 * Return the prefix of dynamic library (e.g. lib)
359 *
360 * @return The prefix string.
361 * @see GetModuleExtension, GetModulesDirectory
362 */
363 static const TCHAR* GetModulePrefix();
364
365 /**
366 * Return the extension of dynamic library
367 *
368 * @return Extension of dynamic library.
369 * @see GetModulePrefix, GetModulesDirectory
370 */
371 static const TCHAR* GetModuleExtension();
372
373 /**
374 * Used only by platforms with DLLs, this gives the subdirectory from binaries to find the executables
375 */
376 static const TCHAR* GetBinariesSubdirectory();
377
378 /**
379 * Used only by platforms with DLLs, this gives the full path to the main directory containing modules
380 *
381 * @return The path to the directory.
382 * @see GetModulePrefix, GetModuleExtension
383 */
385
386 /**
387 * Launch a uniform resource locator (i.e. http://www.epicgames.com/unreal).
388 * This is expected to return immediately as the URL is launched by another
389 * task. The URL param must already be a valid URL. If you're looking for code
390 * to properly escape a URL fragment, use FGenericPlatformHttp::UrlEncode.
391 */
392 static void LaunchURL( const TCHAR* URL, const TCHAR* Parms, FString* Error );
393
394 /**
395 * Launch a uniform resource locator (i.e. http://www.epicgames.com/unreal).
396 * This is expected to return immediately as the URL is launched by another
397 * task. The URL param must already be a valid URL. The URL is passed through
398 * the filter parameter for an added measure of security if the URL is from
399 * and untrusted source. If you're looking for code to properly escape
400 * a URL fragment, use FGenericPlatformHttp::UrlEncode.
401 *
402 * @return true if URL passed the filter and was launched, false if it was rejected by the filter.
403 */
404 static bool LaunchURLFiltered(const TCHAR* URL, const TCHAR* Parms, FString* Error, const UE::Core::FURLRequestFilter& Filter);
405
406 /**
407 * Checks if the platform can launch a uniform resource locator (i.e. http://www.epicgames.com/unreal).
408 **/
409 static bool CanLaunchURL(const TCHAR* URL);
410
411 /**
412 * Retrieves the platform-specific bundle identifier or package name of the game
413 *
414 * @return The game's bundle identifier or package name.
415 */
417
418 /**
419 * Creates a new process and its primary thread. The new process runs the
420 * specified executable file in the security context of the calling process.
421 * @param URL executable name
422 * @param Parms command line arguments
423 * @param bLaunchDetached if true, the new process will have its own window
424 * @param bLaunchHidden if true, the new process will be minimized in the task bar
425 * @param bLaunchReallyHidden if true, the new process will not have a window or be in the task bar
426 * @param OutProcessId if non-NULL, this will be filled in with the ProcessId
427 * @param PriorityModifier -2 idle, -1 low, 0 normal, 1 high, 2 higher
428 * @param OptionalWorkingDirectory Directory to start in when running the program, or NULL to use the current working directory
429 * @param PipeWriteChild Optional HANDLE to pipe for redirecting output
430 * @param PipeReadChild Optional HANDLE to pipe for redirecting input
431 * @return The process handle for use in other process functions
432 */
433 static FProcHandle CreateProc( const TCHAR* URL, const TCHAR* Parms, bool bLaunchDetached, bool bLaunchHidden, bool bLaunchReallyHidden, uint32* OutProcessID, int32 PriorityModifier, const TCHAR* OptionalWorkingDirectory, void* PipeWriteChild, void* PipeReadChild = nullptr);
434
435 /**
436 * Creates a new process and its primary thread, with separate std pipes. The new process runs the
437 * specified executable file in the security context of the calling process.
438 * @param URL executable name
439 * @param Parms command line arguments
440 * @param bLaunchDetached if true, the new process will have its own window
441 * @param bLaunchHidden if true, the new process will be minimized in the task bar
442 * @param bLaunchReallyHidden if true, the new process will not have a window or be in the task bar
443 * @param OutProcessId if non-NULL, this will be filled in with the ProcessId
444 * @param PriorityModifier -2 idle, -1 low, 0 normal, 1 high, 2 higher
445 * @param OptionalWorkingDirectory Directory to start in when running the program, or NULL to use the current working directory
446 * @param PipeWriteChild Optional HANDLE to pipe for redirecting stdout
447 * @param PipeReadChild Optional HANDLE to pipe for redirecting stdin
448 * @param PipeStdErrChild Optional HANDLE to pipe for redirecting stderr
449 * @return The process handle for use in other process functions
450 */
451 static FProcHandle CreateProc( const TCHAR* URL, const TCHAR* Parms, bool bLaunchDetached, bool bLaunchHidden, bool bLaunchReallyHidden, uint32* OutProcessID, int32 PriorityModifier, const TCHAR* OptionalWorkingDirectory, void* PipeWriteChild, void* PipeReadChild, void* PipeStdErrChild);
452
453 /**
454 * Opens an existing process.
455 *
456 * @param ProcessID The process id of the process for which we want to obtain a handle.
457 * @return The process handle for use in other process functions
458 */
459 static FProcHandle OpenProcess(uint32 ProcessID);
460
461 /**
462 * Returns true if the specified process is running
463 *
464 * @param ProcessHandle handle returned from FPlatformProcess::CreateProc
465 * @return true if the process is still running
466 */
467 static bool IsProcRunning( FProcHandle & ProcessHandle );
468
469 /**
470 * Waits for a process to stop
471 *
472 * @param ProcessHandle handle returned from FPlatformProcess::CreateProc
473 */
474 static void WaitForProc( FProcHandle & ProcessHandle );
475
476 /**
477 * Cleans up FProcHandle after we're done with it.
478 *
479 * @param ProcessHandle handle returned from FPlatformProcess::CreateProc.
480 */
481 static void CloseProc( FProcHandle & ProcessHandle );
482
483 /** Terminates a process
484 *
485 * @param ProcessHandle handle returned from FPlatformProcess::CreateProc
486 * @param KillTree Whether the entire process tree should be terminated.
487 */
488 static void TerminateProc( FProcHandle & ProcessHandle, bool KillTree = false );
489
490 /** Terminates a process tree
491 *
492 * @param ProcessHandle handle returned from FPlatformProcess::CreateProc
493 * @param Predicate that returns true if the process identified by ProcessId and ApplicationName
494 * should be terminated with its children, else that process and its children will be kept alive
495 */
497 FProcHandle& ProcessHandle,
498 TFunctionRef<bool(uint32 ProcessId, const TCHAR* ApplicationName)> Predicate);
499
501 {
502 Error,
503 Parent,
504 Child
505 };
506
507 /**
508 * Waits for process signals and forks child processes.
509 *
510 * WaitAndFork stalls the invoking process and forks child processes when signals are sent to it from an external source.
511 * Forked child processes will provide a return value of EWaitAndForkResult::Child, while the parent process
512 * will not return until IsEngineExitRequested() is true (EWaitAndForkResult::Parent) or there was an error (EWaitAndForkResult::Error)
513 * The signal the parent process expects is platform-specific (i.e. SIGRTMIN+1 on Linux).
514 */
516
517 /** Retrieves the termination status of the specified process. **/
518 static bool GetProcReturnCode( FProcHandle & ProcHandle, int32* ReturnCode );
519
520 /** Returns true if the specified application is running */
521 static bool IsApplicationRunning( uint32 ProcessId );
522
523 /** Returns true if the specified application is running */
524 static bool IsApplicationRunning( const TCHAR* ProcName );
525
526 /** Returns the Name of process given by the PID. Returns Empty string "" if PID not found. */
527 static FString GetApplicationName( uint32 ProcessId );
528
529 /** Outputs the virtual memory usage, of the process with the specified PID */
530 static bool GetApplicationMemoryUsage(uint32 ProcessId, SIZE_T* OutMemoryUsage);
531
532 /**
533 * Executes a process, returning the return code, stdout, and stderr. This
534 * call blocks until the process has returned.
535 * @param OutReturnCode may be 0
536 * @param OutStdOut may be 0
537 * @param OutStdErr may be 0
538 * @OptionalWorkingDirectory may be 0
539 * @OptionalbShouldEndWithParentProcess false by default. True to make sure the process is killed with the parent processor (Not Supported on all Platforms)
540 */
541 static bool ExecProcess(const TCHAR* URL, const TCHAR* Params, int32* OutReturnCode, FString* OutStdOut, FString* OutStdErr, const TCHAR* OptionalWorkingDirectory = NULL, bool bShouldEndWithParentProcess = false);
542
543 /**
544 * Executes a process as administrator, requesting elevation as necessary. This
545 * call blocks until the process has returned.
546 */
547 static bool ExecElevatedProcess(const TCHAR* URL, const TCHAR* Params, int32* OutReturnCode);
548
549 /**
550 * Attempt to launch the provided file name in its default external application. Similar to FPlatformProcess::LaunchURL,
551 * with the exception that if a default application isn't found for the file, the user will be prompted with
552 * an "Open With..." dialog.
553 *
554 * @param FileName Name of the file to attempt to launch in its default external application
555 * @param Parms Optional parameters to the default application
556 * @param Verb Optional verb to use when opening the file, if it applies for the platform.
557 * @return true if the file is launched successfully, false otherwise.
558 */
559 static bool LaunchFileInDefaultExternalApplication( const TCHAR* FileName, const TCHAR* Parms = NULL, ELaunchVerb::Type Verb = ELaunchVerb::Open, bool bPromptToOpenOnFailure = true );
560
561 /**
562 * Attempt to "explore" the folder specified by the provided file path
563 *
564 * @param FilePath File path specifying a folder to explore
565 */
566 static void ExploreFolder( const TCHAR* FilePath );
567
569
570 /** Sleep this thread for Seconds. 0.0 means release the current time slice to let other threads get some attention. Uses stats.*/
571 static void Sleep( float Seconds );
572 /** Sleep this thread for Seconds. 0.0 means release the current time slice to let other threads get some attention. */
573 static void SleepNoStats( float Seconds );
574 /** Sleep this thread infinitely. */
575 [[noreturn]] static void SleepInfinite();
576 /** Yield this thread so another may run for a while. */
577 static void YieldThread();
578
579#endif // PLATFORM_HAS_BSD_TIME
580
581 /**
582 * Sleep thread until condition is satisfied.
583 *
584 * @param Condition Condition to evaluate.
585 * @param SleepTime Time to sleep
586 */
587 static void ConditionalSleep(TFunctionRef<bool()> Condition, float SleepTime = 0.0f);
588
589 /**
590 * Creates a new event.
591 *
592 * @param bIsManualReset Whether the event requires manual reseting or not.
593 * @return A new event, or nullptr none could be created.
594 * @see GetSynchEventFromPool, ReturnSynchEventToPool
595 */
596 // Message to others in the future, don't try to delete this function as it isn't exactly deprecated, but it should only ever be called from TEventPool::GetEventFromPool()
597 UE_DEPRECATED(5.0, "Please use GetSynchEventFromPool to create a new event, and ReturnSynchEventToPool to release the event.")
598 static class FEvent* CreateSynchEvent(bool bIsManualReset = false);
599
600 /**
601 * Gets an event from the pool or creates a new one if necessary.
602 *
603 * @param bIsManualReset Whether the event requires manual reseting or not.
604 * @return An event, or nullptr none could be created.
605 * @see CreateSynchEvent, ReturnSynchEventToPool
606 */
607 static class FEvent* GetSynchEventFromPool(bool bIsManualReset = false);
608
609 /**
610 * Deletes all the recycled sync events contained by the pools
611 */
612 static void FlushPoolSyncEvents();
613
614 /**
615 * Returns an event to the pool.
616 *
617 * @param Event The event to return.
618 * @see CreateSynchEvent, GetSynchEventFromPool
619 */
620 static void ReturnSynchEventToPool(FEvent* Event);
621
622 /**
623 * Creates the platform-specific runnable thread. This should only be called from FRunnableThread::Create.
624 *
625 * @return The newly created thread
626 */
628
629 /**
630 * Closes an anonymous pipe.
631 *
632 * @param ReadPipe The handle to the read end of the pipe.
633 * @param WritePipe The handle to the write end of the pipe.
634 * @see CreatePipe, ReadPipe
635 */
636 static void ClosePipe( void* ReadPipe, void* WritePipe );
637
638 /**
639 * Creates a writable anonymous pipe.
640 *
641 * Anonymous pipes can be used to capture and/or redirect STDOUT and STDERROR of a process.
642 * The pipe created by this method can be passed into CreateProc as Write
643 *
644 * @param ReadPipe Will hold the handle to the read end of the pipe.
645 * @param WritePipe Will hold the handle to the write end of the pipe.
646 * @parm bWritePipeLocal indicates that the write pipe end will be used locally, instead of the read pipe
647 * @return true on success, false otherwise.
648 * @see ClosePipe, ReadPipe
649 */
650 static bool CreatePipe(void*& ReadPipe, void*& WritePipe, bool bWritePipeLocal = false);
651
652 /**
653 * Reads all pending data from an anonymous pipe, such as STDOUT or STDERROR of a process.
654 *
655 * @param Pipe The handle to the pipe to read from.
656 * @return A string containing the read data.
657 * @see ClosePipe, CreatePipe
658 */
659 static FString ReadPipe( void* ReadPipe );
660
661 /**
662 * Reads all pending data from an anonymous pipe, such as STDOUT or STDERROR of a process.
663 *
664 * @param Pipe The handle to the pipe to read from.
665 * @param Output The data read.
666 * @return true if successful (i.e. any data was read)
667 * @see ClosePipe, CreatePipe
668 */
669 static bool ReadPipeToArray(void* ReadPipe, TArray<uint8> & Output);
670
671 /**
672 * Sends the message to process through pipe
673 *
674 * @param WritePipe Pipe for writing.
675 * @param Message The message to be written.
676 * @param OutWritten Optional parameter to know how much of the string written.
677 * @return True if all bytes written successfully.
678 * @see CreatePipe, ClosePipe, ReadPipe
679 */
680 static bool WritePipe(void* WritePipe, const FString& Message, FString* OutWritten = nullptr);
681
682 /**
683 * Sends data to process through pipe
684 *
685 * @param WritePipe Pipe for writing.
686 * @param Data The data to be written.
687 * @param DataLength how many bytes to write.
688 * @param OutDataLength Optional parameter to know how many bytes had been written.
689 * @return True if all bytes written successfully.
690 * @see CreatePipe, ClosePipe, ReadPipe
691 */
692 static bool WritePipe(void* WritePipe, const uint8* Data, const int32 DataLength, int32* OutDataLength = nullptr);
693
694
695 /**
696 * Gets whether this platform can use multiple threads.
697 *
698 * @return true if the platform can use multiple threads, false otherwise.
699 */
701
702 /** Enables Real Time Mode on the current thread. */
703 static void SetRealTimeMode() { }
704
705 /**
706 * Creates or opens an interprocess synchronization object.
707 *
708 * @param Name name (so we can use it across processes).
709 * @param bCreate If true, the function will try to create, otherwise will try to open existing.
710 * @param MaxLocks Maximum amount of locks that the semaphore can have (pass 1 to make it act as mutex).
711 * @return Pointer to heap allocated semaphore object. Caller is responsible for deletion.
712 */
713 static FSemaphore* NewInterprocessSynchObject(const FString& Name, bool bCreate, uint32 MaxLocks = 1);
714
715 /**
716 * Creates or opens an interprocess synchronization object.
717 *
718 * @param Name name (so we can use it across processes).
719 * @param bCreate If true, the function will try to create, otherwise will try to open existing.
720 * @param MaxLocks Maximum amount of locks that the semaphore can have (pass 1 to make it act as mutex).
721 * @return Pointer to heap allocated semaphore object. Caller is responsible for deletion.
722 */
723 static FSemaphore* NewInterprocessSynchObject(const TCHAR* Name, bool bCreate, uint32 MaxLocks = 1);
724
725 /**
726 * Deletes an interprocess synchronization object.
727 *
728 * @param Object object to destroy.
729 */
731
732 /**
733 * Makes process run as a system service (daemon), i.e. detaches it from whatever user session it was initially run from.
734 *
735 * @return true if successful, false otherwise.
736 */
737 static bool Daemonize();
738
739 /**
740 * Checks if we're the first instance. An instance can become first if the previous first instance quits before it.
741 */
742 static bool IsFirstInstance();
743
744 /**
745 * Tears down allocated process resources.
746 */
747 static void TearDown();
748
749 /**
750 * force skip calling FThreadStats::WaitForStats()
751 */
752 static bool SkipWaitForStats() { return false; }
753
754 /**
755 * specifies the thread to use for UObject reference collection
756 */
758
759 /**
760 * allows a platform to override the threading configuration for reference collection
761 */
762 static void ModifyThreadAssignmentForUObjectReferenceCollector( int32& NumThreads, int32& NumBackgroundThreads, ENamedThreads::Type& NormalThreadName, ENamedThreads::Type& BackgroundThreadName );
763
764 /**
765 * Tells the processor to pause for implementation-specific amount of time. Is used for spin-loops to improve the speed at
766 * which the code detects the release of the lock and power-consumption.
767 */
768 static FORCEINLINE void Yield()
769 {
771 _mm_pause();
772#elif PLATFORM_CPU_ARM_FAMILY
773# if !defined(__clang__)
774 __yield(); // MSVC
775# else
777# endif
778#else
779# error Unsupported architecture!
780#endif
781 }
782
783 /**
784 * Tells the processor to pause for at least the amount of cycles given. Is used for spin-loops to improve the speed at
785 * which the code detects the release of the lock and power-consumption.
786 */
788 {
790 auto ReadCycleCounter = []()
791 {
792#if defined(_MSC_VER)
793 return __rdtsc();
794#elif PLATFORM_APPLE
795 return mach_absolute_time();
796#elif __has_builtin(__builtin_readcyclecounter)
798#else
799# error Unsupported architecture!
800#endif
801 };
802
804 //some 32bit implementations return 0 for __builtin_readcyclecounter just to be on the safe side we protect against this.
805 Cycles = start != 0 ? Cycles : 0;
806
809 {
811#if defined(_MSC_VER) && !defined(__clang__)
813#elif __has_builtin(__builtin_ia32_tpause)
815#else
816# error Unsupported architecture!
817#endif
818 }
819 else
820#endif
821 {
822 do
823 {
824 Yield();
825 } while ((ReadCycleCounter() - start) < Cycles);
826 }
827
828#else
829 // We can't read cycle counter from user mode on these platform
830 for (uint64 i = 0; i < Cycles; i++)
831 {
832 Yield();
833 }
834#endif
835 }
836};
#define UE_DEPRECATED(Version, Message)
EThreadPriority
Definition Enums.h:5969
EBuildConfiguration
#define PLATFORM_CPU_X86_FAMILY
Definition Platform.h:80
#define PLATFORM_APPLE
Definition Platform.h:44
#define PLATFORM_WINDOWS
Definition Platform.h:4
#define FORCEINLINE
Definition Platform.h:644
#define PLATFORM_HAS_BSD_TIME
Definition Platform.h:271
Definition Event.h:21
Definition Vector.h:40
FSemaphore(const FString &InName)
virtual bool TryLock(uint64 NanosecondsToWait)=0
static void ModifyThreadAssignmentForUObjectReferenceCollector(int32 &NumThreads, int32 &NumBackgroundThreads, ENamedThreads::Type &NormalThreadName, ENamedThreads::Type &BackgroundThreadName)
static const TCHAR * UserDir()
static bool IsApplicationRunning(uint32 ProcessId)
static const TCHAR * GetModulePrefix()
static const TCHAR * ExecutableName(bool bRemoveExtension=true)
static FORCEINLINE void PopDllDirectory(const TCHAR *Directory)
static void SetThreadPriority(EThreadPriority NewPriority)
static void TerminateProc(FProcHandle &ProcessHandle, bool KillTree=false)
static void SetThreadAffinityMask(uint64 AffinityMask)
static FString GenerateApplicationPath(const FString &AppName, EBuildConfiguration BuildConfiguration)
static bool DeleteInterprocessSynchObject(FSemaphore *Object)
static void FreeDllHandle(void *DllHandle)
static bool LaunchFileInDefaultExternalApplication(const TCHAR *FileName, const TCHAR *Parms=NULL, ELaunchVerb::Type Verb=ELaunchVerb::Open, bool bPromptToOpenOnFailure=true)
static FORCEINLINE void PushDllDirectory(const TCHAR *Directory)
static FProcHandle CreateProc(const TCHAR *URL, const TCHAR *Parms, bool bLaunchDetached, bool bLaunchHidden, bool bLaunchReallyHidden, uint32 *OutProcessID, int32 PriorityModifier, const TCHAR *OptionalWorkingDirectory, void *PipeWriteChild, void *PipeReadChild=nullptr)
static class FEvent * GetSynchEventFromPool(bool bIsManualReset=false)
static bool LaunchURLFiltered(const TCHAR *URL, const TCHAR *Parms, FString *Error, const UE::Core::FURLRequestFilter &Filter)
static bool CreatePipe(void *&ReadPipe, void *&WritePipe, bool bWritePipeLocal=false)
static const FString ShaderWorkingDir()
static bool ExecElevatedProcess(const TCHAR *URL, const TCHAR *Params, int32 *OutReturnCode)
static FString GetGameBundleId()
static class FRunnableThread * CreateRunnableThread()
static bool SetProcessLimits(EProcessResource::Type Resource, uint64 Limit)
static FSemaphore * NewInterprocessSynchObject(const TCHAR *Name, bool bCreate, uint32 MaxLocks=1)
static bool ReadPipeToArray(void *ReadPipe, TArray< uint8 > &Output)
static uint32 GetCurrentCoreNumber()
static ENamedThreads::Type GetDesiredThreadForUObjectReferenceCollector()
static bool SupportsMultithreading()
static void * GetDllHandle(const TCHAR *Filename)
static FORCEINLINE void AddDllDirectory(const TCHAR *Directory)
static const TCHAR * UserName(bool bOnlyAlphaNumeric=true)
static FSemaphore * NewInterprocessSynchObject(const FString &Name, bool bCreate, uint32 MaxLocks=1)
static const TCHAR * ShaderDir()
static class FEvent * CreateSynchEvent(bool bIsManualReset=false)
static const TCHAR * UserTempDir()
static bool WritePipe(void *WritePipe, const FString &Message, FString *OutWritten=nullptr)
static EWaitAndForkResult WaitAndFork()
static void SetShaderDir(const TCHAR *Where)
static void DumpThreadInfo(const TCHAR *MarkerName)
static FString GetApplicationName(uint32 ProcessId)
static const TCHAR * ApplicationSettingsDir()
static FORCEINLINE void GetDllDirectories(TArray< FString > &OutDllDirectories)
static void LaunchURL(const TCHAR *URL, const TCHAR *Parms, FString *Error)
static bool GetProcReturnCode(FProcHandle &ProcHandle, int32 *ReturnCode)
static const TCHAR * ComputerName()
static uint32 GetStackSize()
static void SetCurrentWorkingDirectoryToBaseDir()
static void TerminateProcTreeWithPredicate(FProcHandle &ProcessHandle, TFunctionRef< bool(uint32 ProcessId, const TCHAR *ApplicationName)> Predicate)
static const TCHAR * BaseDir()
static FProcHandle CreateProc(const TCHAR *URL, const TCHAR *Parms, bool bLaunchDetached, bool bLaunchHidden, bool bLaunchReallyHidden, uint32 *OutProcessID, int32 PriorityModifier, const TCHAR *OptionalWorkingDirectory, void *PipeWriteChild, void *PipeReadChild, void *PipeStdErrChild)
static void WaitForProc(FProcHandle &ProcessHandle)
static void ClosePipe(void *ReadPipe, void *WritePipe)
static bool ShouldSaveToUserDir()
static FString GetCurrentWorkingDirectory()
static const FString GetModulesDirectory()
static bool Daemonize()
static void ConditionalSleep(TFunctionRef< bool()> Condition, float SleepTime=0.0f)
static bool IsApplicationRunning(const TCHAR *ProcName)
static const TCHAR * UserSettingsDir()
static void CleanShaderWorkingDir()
static void ExploreFolder(const TCHAR *FilePath)
static const TCHAR * GetModuleExtension()
static bool IsFirstInstance()
static void SetThreadName(const TCHAR *ThreadName)
static bool ExecProcess(const TCHAR *URL, const TCHAR *Params, int32 *OutReturnCode, FString *OutStdOut, FString *OutStdErr, const TCHAR *OptionalWorkingDirectory=NULL, bool bShouldEndWithParentProcess=false)
static void TearDown()
static void CloseProc(FProcHandle &ProcessHandle)
static FProcHandle OpenProcess(uint32 ProcessID)
static bool CanLaunchURL(const TCHAR *URL)
static bool IsProcRunning(FProcHandle &ProcessHandle)
static bool WritePipe(void *WritePipe, const uint8 *Data, const int32 DataLength, int32 *OutDataLength=nullptr)
static const TCHAR * ExecutablePath()
static const TCHAR * GetBinariesSubdirectory()
static const TCHAR * UserHomeDir()
static uint32 GetCurrentProcessId()
static bool GetApplicationMemoryUsage(uint32 ProcessId, SIZE_T *OutMemoryUsage)
static void * GetDllExport(void *DllHandle, const TCHAR *ProcName)
static void ReturnSynchEventToPool(FEvent *Event)
static void FlushPoolSyncEvents()
static FString ReadPipe(void *ReadPipe)
FORCEINLINE TProcHandle & operator=(const TProcHandle &Other)
FORCEINLINE TProcHandle(T Other)
FORCEINLINE void Reset()
FORCEINLINE T Get() const
FORCEINLINE TProcHandle()
FORCEINLINE bool IsValid() const