summaryrefslogtreecommitdiffstats
path: root/toolkit/components/backgroundtasks/BackgroundTasksRunner.cpp
blob: 9b950ecf0d461ad10366ffb2ddbc17a0ef1fe5b7 (plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/BackgroundTasksRunner.h"

#include "base/process_util.h"
#include "mozilla/StaticPrefs_toolkit.h"
#include "nsIFile.h"

#ifdef XP_WIN
#  include "mozilla/AssembleCmdLine.h"
#endif

namespace mozilla {

NS_IMPL_ISUPPORTS(BackgroundTasksRunner, nsIBackgroundTasksRunner);

NS_IMETHODIMP BackgroundTasksRunner::RunInDetachedProcess(
    const nsACString& aTaskName, const nsTArray<nsCString>& aArgs) {
  nsCOMPtr<nsIFile> lf;
  nsresult rv = XRE_GetBinaryPath(getter_AddRefs(lf));
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString exePath;
#if !defined(XP_WIN)
  rv = lf->GetNativePath(exePath);
#else
  rv = lf->GetNativeTarget(exePath);
#endif
  NS_ENSURE_SUCCESS(rv, rv);

  base::LaunchOptions options;
#ifdef XP_WIN
  options.start_independent = true;

  nsTArray<const char*> argv = {exePath.Data(), "--backgroundtask",
                                aTaskName.Data()};
  for (const nsCString& str : aArgs) {
    argv.AppendElement(str.get());
  }
  argv.AppendElement(nullptr);

  wchar_t* assembledCmdLine = nullptr;
  if (assembleCmdLine(argv.Elements(), &assembledCmdLine, CP_UTF8) == -1) {
    return NS_ERROR_FAILURE;
  }

  if (!base::LaunchApp(assembledCmdLine, options, nullptr)) {
    return NS_ERROR_FAILURE;
  }
#else
  std::vector<std::string> argv = {exePath.Data(), "--backgroundtask",
                                   aTaskName.Data()};
  for (const nsCString& str : aArgs) {
    argv.push_back(str.get());
  }

  if (!base::LaunchApp(argv, options, nullptr)) {
    return NS_ERROR_FAILURE;
  }
#endif

  return NS_OK;
}

NS_IMETHODIMP BackgroundTasksRunner::RemoveDirectoryInDetachedProcess(
    const nsACString& aParentDirPath, const nsACString& aChildDirName,
    const nsACString& aSecondsToWait, const nsACString& aOtherFoldersSuffix) {
  nsTArray<nsCString> argv = {aParentDirPath + ""_ns, aChildDirName + ""_ns,
                              aSecondsToWait + ""_ns,
                              aOtherFoldersSuffix + ""_ns};

  uint32_t testingSleepMs =
      StaticPrefs::toolkit_background_tasks_remove_directory_testing_sleep_ms();
  if (testingSleepMs > 0) {
    argv.AppendElement("--test-sleep");
    nsAutoCString sleep;
    sleep.AppendInt(testingSleepMs);
    argv.AppendElement(sleep);
  }

  return RunInDetachedProcess("removeDirectory"_ns, argv);
}

}  // namespace mozilla