1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
6#define BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
7
8#include <windows.h>
9
10#include "base/basictypes.h"
11#include "base/base_export.h"
12#include "base/win/scoped_handle.h"
13
14namespace base {
15namespace win {
16
17// Manages the closing of process and thread handles from PROCESS_INFORMATION
18// structures. Allows clients to take ownership of either handle independently.
19class BASE_EXPORT ScopedProcessInformation {
20 public:
21  ScopedProcessInformation();
22  explicit ScopedProcessInformation(const PROCESS_INFORMATION& process_info);
23  ~ScopedProcessInformation();
24
25  // Returns true iff this instance is holding a thread and/or process handle.
26  bool IsValid() const;
27
28  // Closes the held thread and process handles, if any.
29  void Close();
30
31  // Populates this instance with the provided |process_info|.
32  void Set(const PROCESS_INFORMATION& process_info);
33
34  // Populates this instance with duplicate handles and the thread/process IDs
35  // from |other|. Returns false in case of failure, in which case this instance
36  // will be completely unpopulated.
37  bool DuplicateFrom(const ScopedProcessInformation& other);
38
39  // Transfers ownership of the held PROCESS_INFORMATION, if any, away from this
40  // instance.
41  PROCESS_INFORMATION Take();
42
43  // Transfers ownership of the held process handle, if any, away from this
44  // instance. Note that the related process_id will also be cleared.
45  HANDLE TakeProcessHandle();
46
47  // Transfers ownership of the held thread handle, if any, away from this
48  // instance. Note that the related thread_id will also be cleared.
49  HANDLE TakeThreadHandle();
50
51  // Returns the held process handle, if any, while retaining ownership.
52  HANDLE process_handle() const {
53    return process_handle_.Get();
54  }
55
56  // Returns the held thread handle, if any, while retaining ownership.
57  HANDLE thread_handle() const {
58    return thread_handle_.Get();
59  }
60
61  // Returns the held process id, if any.
62  DWORD process_id() const {
63    return process_id_;
64  }
65
66  // Returns the held thread id, if any.
67  DWORD thread_id() const {
68    return thread_id_;
69  }
70
71 private:
72  ScopedHandle process_handle_;
73  ScopedHandle thread_handle_;
74  DWORD process_id_;
75  DWORD thread_id_;
76
77  DISALLOW_COPY_AND_ASSIGN(ScopedProcessInformation);
78};
79
80}  // namespace win
81}  // namespace base
82
83#endif  // BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
84