1 // Copyright 2012 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
26 bool DepsLog::OpenForWrite(const string& path, string* err) {
27 file_ = fopen(path.c_str(), "ab");
29 *err = strerror(errno);
32 SetCloseOnExec(fileno(file_));
34 // Opening a file in append mode doesn't set the file pointer to the file's
35 // end on Windows. Do that explicitly.
36 fseek(file_, 0, SEEK_END);
39 if (ftell(log_file_) == 0) {
40 if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
41 *err = strerror(errno);
50 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
51 const vector<Node*>& nodes) {
52 // Assign ids to all nodes that are missing one.
55 for (vector<Node*>::const_iterator i = nodes.begin();
56 i != nodes.end(); ++i) {
61 uint16_t size = 4 * (1 + 1 + nodes.size());
62 size |= 0x8000; // Deps record: set high bit.
63 fwrite(&size, 2, 1, file_);
65 fwrite(&id, 4, 1, file_);
66 int timestamp = mtime;
67 fwrite(×tamp, 4, 1, file_);
68 for (vector<Node*>::const_iterator i = nodes.begin();
69 i != nodes.end(); ++i) {
71 fwrite(&id, 4, 1, file_);
77 void DepsLog::Close() {
82 bool DepsLog::Load(const string& path, State* state, string* err) {
84 FILE* f = fopen(path.c_str(), "rb");
88 *err = strerror(errno);
94 if (fread(&size, 2, 1, f) < 1)
96 bool is_deps = (size >> 15) != 0;
99 if (fread(buf, size, 1, f) < 1)
103 assert(size % 4 == 0);
104 int* deps_data = reinterpret_cast<int*>(buf);
105 int out_id = deps_data[0];
106 int mtime = deps_data[1];
108 int deps_count = (size / 4) - 2;
110 Deps* deps = new Deps;
112 deps->node_count = deps_count;
113 deps->nodes = new Node*[deps_count];
114 for (int i = 0; i < deps_count; ++i) {
115 assert(deps_data[i] < (int)nodes_.size());
116 assert(nodes_[deps_data[i]]);
117 deps->nodes[i] = nodes_[deps_data[i]];
120 if (out_id >= (int)deps_.size())
121 deps_.resize(out_id + 1);
123 delete deps_[out_id];
124 deps_[out_id] = deps;
126 StringPiece path(buf, size);
127 Node* node = state->GetNode(path);
128 assert(node->id() < 0);
129 node->set_id(nodes_.size());
130 nodes_.push_back(node);
134 *err = strerror(ferror(f));
141 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
144 return deps_[node->id()];
147 bool DepsLog::RecordId(Node* node) {
148 uint16_t size = node->path().size();
149 fwrite(&size, 2, 1, file_);
150 fwrite(node->path().data(), node->path().size(), 1, file_);
152 node->set_id(nodes_.size());
153 nodes_.push_back(node);