Add a 'recompact' tool, which forces recompaction of the build and deps logs.
[platform/upstream/ninja.git] / src / deps_log.cc
1 // Copyright 2012 Google Inc. All Rights Reserved.
2 //
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
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14
15 #include "deps_log.h"
16
17 #include <assert.h>
18 #include <stdio.h>
19 #include <errno.h>
20 #include <string.h>
21 #ifndef _WIN32
22 #include <unistd.h>
23 #endif
24
25 #include "graph.h"
26 #include "metrics.h"
27 #include "state.h"
28 #include "util.h"
29
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;
34
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;
39
40 DepsLog::~DepsLog() {
41   Close();
42 }
43
44 bool DepsLog::OpenForWrite(const string& path, string* err) {
45   if (needs_recompaction_) {
46     if (!Recompact(path, err))
47       return false;
48   }
49   
50   file_ = fopen(path.c_str(), "ab");
51   if (!file_) {
52     *err = strerror(errno);
53     return false;
54   }
55   setvbuf(file_, NULL, _IOFBF, kMaxBufferSize);
56   SetCloseOnExec(fileno(file_));
57
58   // Opening a file in append mode doesn't set the file pointer to the file's
59   // end on Windows. Do that explicitly.
60   fseek(file_, 0, SEEK_END);
61
62   if (ftell(file_) == 0) {
63     if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
64       *err = strerror(errno);
65       return false;
66     }
67     if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
68       *err = strerror(errno);
69       return false;
70     }
71   }
72   fflush(file_);
73
74   return true;
75 }
76
77 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
78                          const vector<Node*>& nodes) {
79   return RecordDeps(node, mtime, nodes.size(),
80                     nodes.empty() ? NULL : (Node**)&nodes.front());
81 }
82
83 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
84                          int node_count, Node** nodes) {
85   // Track whether there's any new data to be recorded.
86   bool made_change = false;
87
88   // Assign ids to all nodes that are missing one.
89   if (node->id() < 0) {
90     RecordId(node);
91     made_change = true;
92   }
93   for (int i = 0; i < node_count; ++i) {
94     if (nodes[i]->id() < 0) {
95       RecordId(nodes[i]);
96       made_change = true;
97     }
98   }
99
100   // See if the new data is different than the existing data, if any.
101   if (!made_change) {
102     Deps* deps = GetDeps(node);
103     if (!deps ||
104         deps->mtime != mtime ||
105         deps->node_count != node_count) {
106       made_change = true;
107     } else {
108       for (int i = 0; i < node_count; ++i) {
109         if (deps->nodes[i] != nodes[i]) {
110           made_change = true;
111           break;
112         }
113       }
114     }
115   }
116
117   // Don't write anything if there's no new info.
118   if (!made_change)
119     return true;
120
121   // Update on-disk representation.
122   uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
123   size |= 0x8000;  // Deps record: set high bit.
124   fwrite(&size, 2, 1, file_);
125   int id = node->id();
126   fwrite(&id, 4, 1, file_);
127   int timestamp = mtime;
128   fwrite(&timestamp, 4, 1, file_);
129   for (int i = 0; i < node_count; ++i) {
130     id = nodes[i]->id();
131     fwrite(&id, 4, 1, file_);
132   }
133   fflush(file_);
134
135   // Update in-memory representation.
136   Deps* deps = new Deps(mtime, node_count);
137   for (int i = 0; i < node_count; ++i)
138     deps->nodes[i] = nodes[i];
139   UpdateDeps(node->id(), deps);
140
141   return true;
142 }
143
144 void DepsLog::Close() {
145   if (file_)
146     fclose(file_);
147   file_ = NULL;
148 }
149
150 bool DepsLog::Load(const string& path, State* state, string* err) {
151   METRIC_RECORD(".ninja_deps load");
152   char buf[32 << 10];
153   FILE* f = fopen(path.c_str(), "rb");
154   if (!f) {
155     if (errno == ENOENT)
156       return true;
157     *err = strerror(errno);
158     return false;
159   }
160
161   bool valid_header = true;
162   int version = 0;
163   if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
164     valid_header = false;
165   if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
166       version != kCurrentVersion) {
167     *err = "bad deps log signature or version; starting over";
168     fclose(f);
169     unlink(path.c_str());
170     // Don't report this as a failure.  An empty deps log will cause
171     // us to rebuild the outputs anyway.
172     return true;
173   }
174
175   long offset;
176   bool read_failed = false;
177   int unique_dep_record_count = 0;
178   int total_dep_record_count = 0;
179   for (;;) {
180     offset = ftell(f);
181
182     uint16_t size;
183     if (fread(&size, 2, 1, f) < 1) {
184       if (!feof(f))
185         read_failed = true;
186       break;
187     }
188     bool is_deps = (size >> 15) != 0;
189     size = size & 0x7FFF;
190
191     if (fread(buf, size, 1, f) < 1) {
192       read_failed = true;
193       break;
194     }
195
196     if (is_deps) {
197       assert(size % 4 == 0);
198       int* deps_data = reinterpret_cast<int*>(buf);
199       int out_id = deps_data[0];
200       int mtime = deps_data[1];
201       deps_data += 2;
202       int deps_count = (size / 4) - 2;
203
204       Deps* deps = new Deps(mtime, deps_count);
205       for (int i = 0; i < deps_count; ++i) {
206         assert(deps_data[i] < (int)nodes_.size());
207         assert(nodes_[deps_data[i]]);
208         deps->nodes[i] = nodes_[deps_data[i]];
209       }
210
211       total_dep_record_count++;
212       if (!UpdateDeps(out_id, deps))
213         ++unique_dep_record_count;
214     } else {
215       StringPiece path(buf, size);
216       Node* node = state->GetNode(path);
217       assert(node->id() < 0);
218       node->set_id(nodes_.size());
219       nodes_.push_back(node);
220     }
221   }
222
223   if (read_failed) {
224     // An error occurred while loading; try to recover by truncating the
225     // file to the last fully-read record.
226     if (ferror(f)) {
227       *err = strerror(ferror(f));
228     } else {
229       *err = "premature end of file";
230     }
231     fclose(f);
232
233     if (!Truncate(path.c_str(), offset, err))
234       return false;
235
236     // The truncate succeeded; we'll just report the load error as a
237     // warning because the build can proceed.
238     *err += "; recovering";
239     return true;
240   }
241
242   fclose(f);
243
244   // Rebuild the log if there are too many dead records.
245   int kMinCompactionEntryCount = 1000;
246   int kCompactionRatio = 3;
247   if (total_dep_record_count > kMinCompactionEntryCount &&
248       total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
249     needs_recompaction_ = true;
250   }
251
252   return true;
253 }
254
255 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
256   // Abort if the node has no id (never referenced in the deps) or if
257   // there's no deps recorded for the node.
258   if (node->id() < 0 || node->id() >= (int)deps_.size())
259     return NULL;
260   return deps_[node->id()];
261 }
262
263 bool DepsLog::Recompact(const string& path, string* err) {
264   METRIC_RECORD(".ninja_deps recompact");
265   printf("Recompacting deps...\n");
266
267   Close();
268   string temp_path = path + ".recompact";
269
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());
273
274   DepsLog new_log;
275   if (!new_log.OpenForWrite(temp_path, err))
276     return false;
277
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)
281     (*i)->set_id(-1);
282   
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.
287
288     if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
289                             deps->node_count, deps->nodes)) {
290       new_log.Close();
291       return false;
292     }
293   }
294
295   new_log.Close();
296
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_);
300
301   if (unlink(path.c_str()) < 0) {
302     *err = strerror(errno);
303     return false;
304   }
305
306   if (rename(temp_path.c_str(), path.c_str()) < 0) {
307     *err = strerror(errno);
308     return false;
309   }
310
311   return true;
312 }
313
314 bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
315   if (out_id >= (int)deps_.size())
316     deps_.resize(out_id + 1);
317
318   bool delete_old = deps_[out_id] != NULL;
319   if (delete_old)
320     delete deps_[out_id];
321   deps_[out_id] = deps;
322   return delete_old;
323 }
324
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_);
329   fflush(file_);
330
331   node->set_id(nodes_.size());
332   nodes_.push_back(node);
333
334   return true;
335 }