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.
30 // The version is stored as 4 bytes after the signature and also serves as a
31 // byte order mark. Signature and version combined are 16 bytes long.
32 const char kFileSignature[] = "# ninjadeps\n";
33 const int kCurrentVersion = 1;
35 // Since the size field is 2 bytes and the top bit marks deps entries, a single
36 // record can be at most 32 kB. Set the buffer size to this and flush the file
37 // buffer after every record to make sure records aren't written partially.
38 const int kMaxBufferSize = 1 << 15;
44 bool DepsLog::OpenForWrite(const string& path, string* err) {
45 if (needs_recompaction_) {
47 if (!Recompact(path, err))
51 file_ = fopen(path.c_str(), "ab");
53 *err = strerror(errno);
56 setvbuf(file_, NULL, _IOFBF, kMaxBufferSize);
57 SetCloseOnExec(fileno(file_));
59 // Opening a file in append mode doesn't set the file pointer to the file's
60 // end on Windows. Do that explicitly.
61 fseek(file_, 0, SEEK_END);
63 if (ftell(file_) == 0) {
64 if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
65 *err = strerror(errno);
68 if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
69 *err = strerror(errno);
78 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
79 const vector<Node*>& nodes) {
80 return RecordDeps(node, mtime, nodes.size(),
81 nodes.empty() ? NULL : (Node**)&nodes.front());
84 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
85 int node_count, Node** nodes) {
86 // Track whether there's any new data to be recorded.
87 bool made_change = false;
89 // Assign ids to all nodes that are missing one.
94 for (int i = 0; i < node_count; ++i) {
95 if (nodes[i]->id() < 0) {
101 // See if the new data is different than the existing data, if any.
103 Deps* deps = GetDeps(node);
105 deps->mtime != mtime ||
106 deps->node_count != node_count) {
109 for (int i = 0; i < node_count; ++i) {
110 if (deps->nodes[i] != nodes[i]) {
118 // Don't write anything if there's no new info.
122 // Update on-disk representation.
123 uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
124 size |= 0x8000; // Deps record: set high bit.
125 fwrite(&size, 2, 1, file_);
127 fwrite(&id, 4, 1, file_);
128 int timestamp = mtime;
129 fwrite(×tamp, 4, 1, file_);
130 for (int i = 0; i < node_count; ++i) {
132 fwrite(&id, 4, 1, file_);
136 // Update in-memory representation.
137 Deps* deps = new Deps(mtime, node_count);
138 for (int i = 0; i < node_count; ++i)
139 deps->nodes[i] = nodes[i];
140 UpdateDeps(node->id(), deps);
145 void DepsLog::Close() {
151 bool DepsLog::Load(const string& path, State* state, string* err) {
152 METRIC_RECORD(".ninja_deps load");
154 FILE* f = fopen(path.c_str(), "rb");
158 *err = strerror(errno);
162 bool valid_header = true;
164 if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
165 valid_header = false;
166 if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
167 version != kCurrentVersion) {
168 *err = "bad deps log signature or version; starting over";
170 unlink(path.c_str());
171 // Don't report this as a failure. An empty deps log will cause
172 // us to rebuild the outputs anyway.
177 bool read_failed = false;
178 int unique_dep_record_count = 0;
179 int total_dep_record_count = 0;
184 if (fread(&size, 2, 1, f) < 1) {
189 bool is_deps = (size >> 15) != 0;
190 size = size & 0x7FFF;
192 if (fread(buf, size, 1, f) < 1) {
198 assert(size % 4 == 0);
199 int* deps_data = reinterpret_cast<int*>(buf);
200 int out_id = deps_data[0];
201 int mtime = deps_data[1];
203 int deps_count = (size / 4) - 2;
205 Deps* deps = new Deps(mtime, deps_count);
206 for (int i = 0; i < deps_count; ++i) {
207 assert(deps_data[i] < (int)nodes_.size());
208 assert(nodes_[deps_data[i]]);
209 deps->nodes[i] = nodes_[deps_data[i]];
212 total_dep_record_count++;
213 if (!UpdateDeps(out_id, deps))
214 ++unique_dep_record_count;
216 StringPiece path(buf, size);
217 Node* node = state->GetNode(path);
218 assert(node->id() < 0);
219 node->set_id(nodes_.size());
220 nodes_.push_back(node);
225 // An error occurred while loading; try to recover by truncating the
226 // file to the last fully-read record.
228 *err = strerror(ferror(f));
230 *err = "premature end of file";
234 if (!Truncate(path.c_str(), offset, err))
237 // The truncate succeeded; we'll just report the load error as a
238 // warning because the build can proceed.
239 *err += "; recovering";
245 // Rebuild the log if there are too many dead records.
246 int kMinCompactionEntryCount = 1000;
247 int kCompactionRatio = 3;
248 if (total_dep_record_count > kMinCompactionEntryCount &&
249 total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
250 needs_recompaction_ = true;
256 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
257 // Abort if the node has no id (never referenced in the deps) or if
258 // there's no deps recorded for the node.
259 if (node->id() < 0 || node->id() >= (int)deps_.size())
261 return deps_[node->id()];
264 bool DepsLog::Recompact(const string& path, string* err) {
265 METRIC_RECORD(".ninja_deps recompact");
266 printf("Recompacting deps...\n");
268 string temp_path = path + ".recompact";
270 // OpenForWrite() opens for append. Make sure it's not appending to a
271 // left-over file from a previous recompaction attempt that crashed somehow.
272 unlink(temp_path.c_str());
275 if (!new_log.OpenForWrite(temp_path, err))
278 // Clear all known ids so that new ones can be reassigned. The new indices
279 // will refer to the ordering in new_log, not in the current log.
280 for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
283 // Write out all deps again.
284 for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
285 Deps* deps = deps_[old_id];
286 if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps.
288 if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
289 deps->node_count, deps->nodes)) {
297 // All nodes now have ids that refer to new_log, so steal its data.
298 deps_.swap(new_log.deps_);
299 nodes_.swap(new_log.nodes_);
301 if (unlink(path.c_str()) < 0) {
302 *err = strerror(errno);
306 if (rename(temp_path.c_str(), path.c_str()) < 0) {
307 *err = strerror(errno);
314 bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
315 if (out_id >= (int)deps_.size())
316 deps_.resize(out_id + 1);
318 bool delete_old = deps_[out_id] != NULL;
320 delete deps_[out_id];
321 deps_[out_id] = deps;
325 bool DepsLog::RecordId(Node* node) {
326 uint16_t size = (uint16_t)node->path().size();
327 fwrite(&size, 2, 1, file_);
328 fwrite(node->path().data(), node->path().size(), 1, file_);
331 node->set_id(nodes_.size());
332 nodes_.push_back(node);