summaryrefslogtreecommitdiff
path: root/NonInheritingProcess.cpp
blob: 5501f5a2c877b1e7d78f1132811b80de808f7c1f (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include "NonInheritingProcess.hpp"

#ifdef Q_OS_WIN
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0601
#include <windows.h>
#endif

#include <memory>
#include <functional>

#include "pimpl_impl.hpp"

namespace
{
#ifdef Q_OS_WIN
  struct start_info_deleter
  {
    void operator () (STARTUPINFOEXW * si)
    {
      if (si->lpAttributeList)
        {
          ::DeleteProcThreadAttributeList (si->lpAttributeList);
        }
      delete si;
    }
  };
#endif
}

class NonInheritingProcess::impl
{
public:
#ifdef Q_OS_WIN
  impl ()
    : job_ {nullptr}
  {
    job_ = ::CreateJobObjectW (nullptr, nullptr);
    if (job_)
      {
        JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits {};
        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        if (!::SetInformationJobObject (job_, JobObjectExtendedLimitInformation,
                                        &limits, sizeof limits))
          {
            ::CloseHandle (job_);
            job_ = nullptr;
          }
      }
  }

  ~impl ()
  {
    if (job_)
      {
        ::CloseHandle (job_);
      }
  }

  void assign_to_job (qint64 process_id)
  {
    if (!job_ || process_id <= 0) return;

    HANDLE process = ::OpenProcess (PROCESS_SET_QUOTA | PROCESS_TERMINATE,
                                    FALSE, static_cast<DWORD> (process_id));
    if (process)
      {
        ::AssignProcessToJobObject (job_, process);
        ::CloseHandle (process);
      }
  }

  void extend_CreateProcessArguments (QProcess::CreateProcessArguments * args)
  {
    // 
    //   Here we modify the  CreateProcessArguments structure to use a
    // STARTUPINFOEX extended  argument to  CreateProcess. In  that we
    // set up  a list of  handles for the  new process to  inherit. By
    // doing   this  we   stop  all   inherited  handles   from  being
    // inherited. Unfortunately UpdateProcThreadAttribute does not let
    // us set  up an empty handle  list, so we populate  the list with
    // the three standard stream  handles that QProcess::start has set
    // up  as Pipes  to do  IPC. Even  though these  Pipe handles  are
    // created with inheritance disabled, UpdateProcThreadAtribute and
    // CreateProcess don't seem to mind, which suits us fine.
    //
    // Note: that we cannot just clear the inheritHandles flag as that
    // stops the standard stream  handles being inherited which breaks
    // our   IPC    using   std(in|out|err).    Only   be    using   a
    // PROC_THREAD_ATTRIBUTE_HANDLE_LIST attribute  in a STARTUPINFOEX
    // structure  can  we  avoid  the  all  or  nothing  behaviour  of
    // CreateProcess /w respect to handle inheritance.
    // 
    BOOL fSuccess;
    SIZE_T size {0};
    LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList = nullptr;
    ::InitializeProcThreadAttributeList (nullptr, 1, 0, &size);
    lpAttributeList = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST> (::HeapAlloc (::GetProcessHeap (), 0, size));
    fSuccess = !!lpAttributeList;
    if (fSuccess)
      {
        fSuccess = ::InitializeProcThreadAttributeList (lpAttributeList, 1, 0, &size);
      }
    if (fSuccess)
      {
        // empty list of handles
        fSuccess = ::UpdateProcThreadAttribute (lpAttributeList, 0,
                                                PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
                                                &args->startupInfo->hStdInput, 3 * sizeof (HANDLE),
                                                nullptr, 0);
      }
    if (fSuccess)
      {
        start_info_.reset (new STARTUPINFOEXW);
        start_info_->StartupInfo = *args->startupInfo;
        start_info_->StartupInfo.cb = sizeof (STARTUPINFOEXW);
        start_info_->lpAttributeList = lpAttributeList;
        args->startupInfo = reinterpret_cast<Q_STARTUPINFO*> (start_info_.get ());
        args->flags |= EXTENDED_STARTUPINFO_PRESENT;
      }
  }

  using start_info_type = std::unique_ptr<STARTUPINFOEXW, start_info_deleter>;
  start_info_type start_info_;
  HANDLE job_;
#endif
};

NonInheritingProcess::NonInheritingProcess (QObject * parent)
  : QProcess {parent}
{
#ifdef Q_OS_WIN
  using namespace std::placeholders;

  // enable cleanup after process starts or fails to start
  connect (this, &QProcess::started, [this] {
    m_->start_info_.reset ();
    m_->assign_to_job (processId ());
  });
  connect (this, &QProcess::errorOccurred, [this] (QProcess::ProcessError) {m_->start_info_.reset ();});
  setCreateProcessArgumentsModifier (std::bind (&NonInheritingProcess::impl::extend_CreateProcessArguments, &*m_, _1));
#endif
}

NonInheritingProcess::~NonInheritingProcess ()
{
}