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.
27 bool DepsLog::OpenForWrite(const string& path, string* err) {
28 file_ = fopen(path.c_str(), "ab");
30 *err = strerror(errno);
33 SetCloseOnExec(fileno(file_));
35 // Opening a file in append mode doesn't set the file pointer to the file's
36 // end on Windows. Do that explicitly.
37 fseek(file_, 0, SEEK_END);
40 if (ftell(log_file_) == 0) {
41 if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) {
42 *err = strerror(errno);
51 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
52 const vector<Node*>& nodes) {
53 // Assign ids to all nodes that are missing one.
56 for (vector<Node*>::const_iterator i = nodes.begin();
57 i != nodes.end(); ++i) {
62 uint16_t size = 4 * (1 + 1 + nodes.size());
63 size |= 0x8000; // Deps record: set high bit.
64 fwrite(&size, 2, 1, file_);
66 fwrite(&id, 4, 1, file_);
67 int timestamp = mtime;
68 fwrite(×tamp, 4, 1, file_);
69 for (vector<Node*>::const_iterator i = nodes.begin();
70 i != nodes.end(); ++i) {
72 fwrite(&id, 4, 1, file_);
78 void DepsLog::Close() {
83 bool DepsLog::Load(const string& path, State* state, string* err) {
84 METRIC_RECORD(".ninja_deps load");
86 FILE* f = fopen(path.c_str(), "rb");
90 *err = strerror(errno);
96 if (fread(&size, 2, 1, f) < 1)
98 bool is_deps = (size >> 15) != 0;
101 if (fread(buf, size, 1, f) < 1)
105 assert(size % 4 == 0);
106 int* deps_data = reinterpret_cast<int*>(buf);
107 int out_id = deps_data[0];
108 int mtime = deps_data[1];
110 int deps_count = (size / 4) - 2;
112 Deps* deps = new Deps;
114 deps->node_count = deps_count;
115 deps->nodes = new Node*[deps_count];
116 for (int i = 0; i < deps_count; ++i) {
117 assert(deps_data[i] < (int)nodes_.size());
118 assert(nodes_[deps_data[i]]);
119 deps->nodes[i] = nodes_[deps_data[i]];
122 if (out_id >= (int)deps_.size())
123 deps_.resize(out_id + 1);
125 delete deps_[out_id];
126 deps_[out_id] = deps;
128 StringPiece path(buf, size);
129 Node* node = state->GetNode(path);
130 assert(node->id() < 0);
131 node->set_id(nodes_.size());
132 nodes_.push_back(node);
136 *err = strerror(ferror(f));
143 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
146 return deps_[node->id()];
149 bool DepsLog::RecordId(Node* node) {
150 uint16_t size = node->path().size();
151 fwrite(&size, 2, 1, file_);
152 fwrite(node->path().data(), node->path().size(), 1, file_);
154 node->set_id(nodes_.size());
155 nodes_.push_back(node);