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;
39 bool DepsLog::OpenForWrite(const string& path, string* err) {
40 if (needs_recompaction_) {
42 if (!Recompact(path, err))
46 file_ = fopen(path.c_str(), "ab");
48 *err = strerror(errno);
51 SetCloseOnExec(fileno(file_));
53 // Opening a file in append mode doesn't set the file pointer to the file's
54 // end on Windows. Do that explicitly.
55 fseek(file_, 0, SEEK_END);
57 if (ftell(file_) == 0) {
58 if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
59 *err = strerror(errno);
62 if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
63 *err = strerror(errno);
71 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
72 const vector<Node*>& nodes) {
73 return RecordDeps(node, mtime, nodes.size(),
74 nodes.empty() ? NULL : (Node**)&nodes.front());
77 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
78 int node_count, Node** nodes) {
79 // Track whether there's any new data to be recorded.
80 bool made_change = false;
82 // Assign ids to all nodes that are missing one.
87 for (int i = 0; i < node_count; ++i) {
88 if (nodes[i]->id() < 0) {
94 // See if the new data is different than the existing data, if any.
96 Deps* deps = GetDeps(node);
98 deps->mtime != mtime ||
99 deps->node_count != node_count) {
102 for (int i = 0; i < node_count; ++i) {
103 if (deps->nodes[i] != nodes[i]) {
111 // Don't write anything if there's no new info.
115 // Update on-disk representation.
116 uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
117 size |= 0x8000; // Deps record: set high bit.
118 fwrite(&size, 2, 1, file_);
120 fwrite(&id, 4, 1, file_);
121 int timestamp = mtime;
122 fwrite(×tamp, 4, 1, file_);
123 for (int i = 0; i < node_count; ++i) {
125 fwrite(&id, 4, 1, file_);
128 // Update in-memory representation.
129 Deps* deps = new Deps(mtime, node_count);
130 for (int i = 0; i < node_count; ++i)
131 deps->nodes[i] = nodes[i];
132 UpdateDeps(node->id(), deps);
137 void DepsLog::Close() {
143 bool DepsLog::Load(const string& path, State* state, string* err) {
144 METRIC_RECORD(".ninja_deps load");
146 FILE* f = fopen(path.c_str(), "rb");
150 *err = strerror(errno);
154 bool valid_header = true;
156 if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
157 valid_header = false;
158 if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
159 version != kCurrentVersion) {
160 *err = "bad deps log signature or version; starting over";
162 unlink(path.c_str());
163 // Don't report this as a failure. An empty deps log will cause
164 // us to rebuild the outputs anyway.
169 bool read_failed = false;
170 int unique_dep_record_count = 0;
171 int total_dep_record_count = 0;
176 if (fread(&size, 2, 1, f) < 1) {
181 bool is_deps = (size >> 15) != 0;
182 size = size & 0x7FFF;
184 if (fread(buf, size, 1, f) < 1) {
190 assert(size % 4 == 0);
191 int* deps_data = reinterpret_cast<int*>(buf);
192 int out_id = deps_data[0];
193 int mtime = deps_data[1];
195 int deps_count = (size / 4) - 2;
197 Deps* deps = new Deps(mtime, deps_count);
198 for (int i = 0; i < deps_count; ++i) {
199 assert(deps_data[i] < (int)nodes_.size());
200 assert(nodes_[deps_data[i]]);
201 deps->nodes[i] = nodes_[deps_data[i]];
204 total_dep_record_count++;
205 if (!UpdateDeps(out_id, deps))
206 ++unique_dep_record_count;
208 StringPiece path(buf, size);
209 Node* node = state->GetNode(path);
210 assert(node->id() < 0);
211 node->set_id(nodes_.size());
212 nodes_.push_back(node);
217 // An error occurred while loading; try to recover by truncating the
218 // file to the last fully-read record.
220 *err = strerror(ferror(f));
222 *err = "premature end of file";
226 if (!Truncate(path.c_str(), offset, err))
229 // The truncate succeeded; we'll just report the load error as a
230 // warning because the build can proceed.
231 *err += "; recovering";
237 // Rebuild the log if there are too many dead records.
238 int kMinCompactionEntryCount = 1000;
239 int kCompactionRatio = 3;
240 if (total_dep_record_count > kMinCompactionEntryCount &&
241 total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
242 needs_recompaction_ = true;
248 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
249 // Abort if the node has no id (never referenced in the deps) or if
250 // there's no deps recorded for the node.
251 if (node->id() < 0 || node->id() >= (int)deps_.size())
253 return deps_[node->id()];
256 bool DepsLog::Recompact(const string& path, string* err) {
257 METRIC_RECORD(".ninja_deps recompact");
258 printf("Recompacting deps...\n");
260 string temp_path = path + ".recompact";
262 // OpenForWrite() opens for append. Make sure it's not appending to a
263 // left-over file from a previous recompaction attempt that crashed somehow.
264 unlink(temp_path.c_str());
267 if (!new_log.OpenForWrite(temp_path, err))
270 // Clear all known ids so that new ones can be reassigned. The new indices
271 // will refer to the ordering in new_log, not in the current log.
272 for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
275 // Write out all deps again.
276 for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
277 Deps* deps = deps_[old_id];
278 if (!deps) continue; // If nodes_[old_id] is a leaf, it has no deps.
280 if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
281 deps->node_count, deps->nodes)) {
289 // All nodes now have ids that refer to new_log, so steal its data.
290 deps_.swap(new_log.deps_);
291 nodes_.swap(new_log.nodes_);
293 if (unlink(path.c_str()) < 0) {
294 *err = strerror(errno);
298 if (rename(temp_path.c_str(), path.c_str()) < 0) {
299 *err = strerror(errno);
306 bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
307 if (out_id >= (int)deps_.size())
308 deps_.resize(out_id + 1);
310 bool delete_old = deps_[out_id] != NULL;
312 delete deps_[out_id];
313 deps_[out_id] = deps;
317 bool DepsLog::RecordId(Node* node) {
318 uint16_t size = (uint16_t)node->path().size();
319 fwrite(&size, 2, 1, file_);
320 fwrite(node->path().data(), node->path().size(), 1, file_);
322 node->set_id(nodes_.size());
323 nodes_.push_back(node);