aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/platform/windows/env.cc
blob: fa3d6a830188c1d2c6cd67ddf4901962f4c62a10 (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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/platform/env.h"

#include <Shlwapi.h>
#include <Windows.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <time.h>
#undef LoadLibrary
#undef ERROR

#include <thread>
#include <vector>
#include <string>

#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/platform/load_library.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/windows/windows_file_system.h"

#pragma comment(lib, "Shlwapi.lib")

namespace tensorflow {

namespace {

class StdThread : public Thread {
 public:
  // name and thread_options are both ignored.
  StdThread(const ThreadOptions& thread_options, const string& name,
            std::function<void()> fn)
      : thread_(fn) {}
  ~StdThread() { thread_.join(); }

 private:
  std::thread thread_;
};

class WindowsEnv : public Env {
 public:
  WindowsEnv()
      : GetSystemTimePreciseAsFileTime_(NULL) {
    // GetSystemTimePreciseAsFileTime function is only available in the latest
    // versions of Windows. For that reason, we try to look it up in
    // kernel32.dll at runtime and use an alternative option if the function
    // is not available.
    HMODULE module = GetModuleHandle("kernel32.dll");
    if (module != NULL) {
      auto func = (FnGetSystemTimePreciseAsFileTime)GetProcAddress(
          module, "GetSystemTimePreciseAsFileTime");
      GetSystemTimePreciseAsFileTime_ = func;
    }
  }

  ~WindowsEnv() override {
    LOG(FATAL) << "Env::Default() must not be destroyed";
  }

  bool MatchPath(const string& path, const string& pattern) override {
    return PathMatchSpec(path.c_str(), pattern.c_str()) == TRUE;
  }

  void SleepForMicroseconds(int64 micros) override { Sleep(micros / 1000); }

  Thread* StartThread(const ThreadOptions& thread_options, const string& name,
                      std::function<void()> fn) override {
    return new StdThread(thread_options, name, fn);
  }

  static VOID CALLBACK SchedClosureCallback(PTP_CALLBACK_INSTANCE Instance,
                                            PVOID Context, PTP_WORK Work) {
    CloseThreadpoolWork(Work);
    std::function<void()>* f = (std::function<void()>*)Context;
    (*f)();
    delete f;
  }
  void SchedClosure(std::function<void()> closure) override {
    PTP_WORK work = CreateThreadpoolWork(
        SchedClosureCallback, new std::function<void()>(std::move(closure)),
        nullptr);
    SubmitThreadpoolWork(work);
  }

  static VOID CALLBACK SchedClosureAfterCallback(PTP_CALLBACK_INSTANCE Instance,
                                                 PVOID Context,
                                                 PTP_TIMER Timer) {
    CloseThreadpoolTimer(Timer);
    std::function<void()>* f = (std::function<void()>*)Context;
    (*f)();
    delete f;
  }

  void SchedClosureAfter(int64 micros, std::function<void()> closure) override {
    PTP_TIMER timer = CreateThreadpoolTimer(
        SchedClosureAfterCallback,
        new std::function<void()>(std::move(closure)), nullptr);
    // in 100 nanosecond units
    FILETIME FileDueTime;
    ULARGE_INTEGER ulDueTime;
    // Negative indicates the amount of time to wait is relative to the current
    // time.
    ulDueTime.QuadPart = (ULONGLONG) - (10 * micros);
    FileDueTime.dwHighDateTime = ulDueTime.HighPart;
    FileDueTime.dwLowDateTime = ulDueTime.LowPart;
    SetThreadpoolTimer(timer, &FileDueTime, 0, 0);
  }

  Status LoadLibrary(const char *library_filename, void** handle) override {
    std::string file_name = library_filename;
    std::replace(file_name.begin(), file_name.end(), '/', '\\');

    HMODULE hModule = LoadLibraryEx(file_name.c_str(), NULL,
      LOAD_WITH_ALTERED_SEARCH_PATH);
    if (!hModule) {
      return errors::NotFound(file_name + " not found");
    }
    *handle = hModule;
    return Status::OK();
  }

  Status GetSymbolFromLibrary(void* handle, const char* symbol_name,
    void** symbol) override {
    FARPROC found_symbol;

    found_symbol = GetProcAddress((HMODULE)handle, symbol_name);
    if (found_symbol == NULL) {
      return errors::NotFound(std::string(symbol_name) + " not found");
    }
    *symbol = (void **)found_symbol;
    return Status::OK();
  }

  string FormatLibraryFileName(const string& name, const string& version)
    override {
    string filename;
    if (version.size() == 0) {
      filename = name + ".dll";
    }
    else {
      filename = name + version + ".dll";
    }
    return filename;
  }

 private:
  typedef VOID(WINAPI * FnGetSystemTimePreciseAsFileTime)(LPFILETIME);
  FnGetSystemTimePreciseAsFileTime GetSystemTimePreciseAsFileTime_;
};

}  // namespace

REGISTER_FILE_SYSTEM("", WindowsFileSystem);
REGISTER_FILE_SYSTEM("file", LocalWinFileSystem);

Env* Env::Default() {
  static Env* default_env = new WindowsEnv;
  return default_env;
}

}  // namespace tensorflow