Adding checks for record overflow in deps_log
[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 // Record size is currently limited to 15 bit
41 const size_t kMaxRecordSize = (1 << 15) - 1;
42
43 DepsLog::~DepsLog() {
44   Close();
45 }
46
47 bool DepsLog::OpenForWrite(const string& path, string* err) {
48   if (needs_recompaction_) {
49     Close();
50     if (!Recompact(path, err))
51       return false;
52   }
53   
54   file_ = fopen(path.c_str(), "ab");
55   if (!file_) {
56     *err = strerror(errno);
57     return false;
58   }
59   setvbuf(file_, NULL, _IOFBF, kMaxBufferSize);
60   SetCloseOnExec(fileno(file_));
61
62   // Opening a file in append mode doesn't set the file pointer to the file's
63   // end on Windows. Do that explicitly.
64   fseek(file_, 0, SEEK_END);
65
66   if (ftell(file_) == 0) {
67     if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
68       *err = strerror(errno);
69       return false;
70     }
71     if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
72       *err = strerror(errno);
73       return false;
74     }
75   }
76   if (fflush(file_) != 0) {
77     *err = strerror(errno);
78     return false;
79   }
80   return true;
81 }
82
83 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
84                          const vector<Node*>& nodes) {
85   return RecordDeps(node, mtime, nodes.size(),
86                     nodes.empty() ? NULL : (Node**)&nodes.front());
87 }
88
89 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
90                          int node_count, Node** nodes) {
91   // Track whether there's any new data to be recorded.
92   bool made_change = false;
93
94   // Assign ids to all nodes that are missing one.
95   if (node->id() < 0) {
96     if (!RecordId(node))
97       return false;
98     made_change = true;
99   }
100   for (int i = 0; i < node_count; ++i) {
101     if (nodes[i]->id() < 0) {
102       if (!RecordId(nodes[i]))
103         return false;
104       made_change = true;
105     }
106   }
107
108   // See if the new data is different than the existing data, if any.
109   if (!made_change) {
110     Deps* deps = GetDeps(node);
111     if (!deps ||
112         deps->mtime != mtime ||
113         deps->node_count != node_count) {
114       made_change = true;
115     } else {
116       for (int i = 0; i < node_count; ++i) {
117         if (deps->nodes[i] != nodes[i]) {
118           made_change = true;
119           break;
120         }
121       }
122     }
123   }
124
125   // Don't write anything if there's no new info.
126   if (!made_change)
127     return true;
128
129   // Update on-disk representation.
130   size_t size = 4 * (1 + 1 + (uint16_t)node_count);
131   if (size > kMaxRecordSize) {
132     errno = ERANGE;
133     return false;
134   }
135   size |= 0x8000;  // Deps record: set high bit.
136   uint16_t size16 = (uint16_t)size;
137   if (fwrite(&size16, 2, 1, file_) < 1)
138     return false;
139   int id = node->id();
140   if (fwrite(&id, 4, 1, file_) < 1)
141     return false;
142   int timestamp = mtime;
143   if (fwrite(&timestamp, 4, 1, file_) < 1)
144     return false;
145   for (int i = 0; i < node_count; ++i) {
146     id = nodes[i]->id();
147     if (fwrite(&id, 4, 1, file_) < 1)
148       return false;
149   }
150   if (fflush(file_) != 0)
151       return false;
152
153   // Update in-memory representation.
154   Deps* deps = new Deps(mtime, node_count);
155   for (int i = 0; i < node_count; ++i)
156     deps->nodes[i] = nodes[i];
157   UpdateDeps(node->id(), deps);
158
159   return true;
160 }
161
162 void DepsLog::Close() {
163   if (file_)
164     fclose(file_);
165   file_ = NULL;
166 }
167
168 bool DepsLog::Load(const string& path, State* state, string* err) {
169   METRIC_RECORD(".ninja_deps load");
170   char buf[32 << 10];
171   FILE* f = fopen(path.c_str(), "rb");
172   if (!f) {
173     if (errno == ENOENT)
174       return true;
175     *err = strerror(errno);
176     return false;
177   }
178
179   bool valid_header = true;
180   int version = 0;
181   if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
182     valid_header = false;
183   if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
184       version != kCurrentVersion) {
185     *err = "bad deps log signature or version; starting over";
186     fclose(f);
187     unlink(path.c_str());
188     // Don't report this as a failure.  An empty deps log will cause
189     // us to rebuild the outputs anyway.
190     return true;
191   }
192
193   long offset;
194   bool read_failed = false;
195   int unique_dep_record_count = 0;
196   int total_dep_record_count = 0;
197   for (;;) {
198     offset = ftell(f);
199
200     uint16_t size;
201     if (fread(&size, 2, 1, f) < 1) {
202       if (!feof(f))
203         read_failed = true;
204       break;
205     }
206     bool is_deps = (size >> 15) != 0;
207     size = size & 0x7FFF;
208
209     if (fread(buf, size, 1, f) < 1) {
210       read_failed = true;
211       break;
212     }
213
214     if (is_deps) {
215       assert(size % 4 == 0);
216       int* deps_data = reinterpret_cast<int*>(buf);
217       int out_id = deps_data[0];
218       int mtime = deps_data[1];
219       deps_data += 2;
220       int deps_count = (size / 4) - 2;
221
222       Deps* deps = new Deps(mtime, deps_count);
223       for (int i = 0; i < deps_count; ++i) {
224         assert(deps_data[i] < (int)nodes_.size());
225         assert(nodes_[deps_data[i]]);
226         deps->nodes[i] = nodes_[deps_data[i]];
227       }
228
229       total_dep_record_count++;
230       if (!UpdateDeps(out_id, deps))
231         ++unique_dep_record_count;
232     } else {
233       StringPiece path(buf, size);
234       Node* node = state->GetNode(path);
235       assert(node->id() < 0);
236       node->set_id(nodes_.size());
237       nodes_.push_back(node);
238     }
239   }
240
241   if (read_failed) {
242     // An error occurred while loading; try to recover by truncating the
243     // file to the last fully-read record.
244     if (ferror(f)) {
245       *err = strerror(ferror(f));
246     } else {
247       *err = "premature end of file";
248     }
249     fclose(f);
250
251     if (!Truncate(path.c_str(), offset, err))
252       return false;
253
254     // The truncate succeeded; we'll just report the load error as a
255     // warning because the build can proceed.
256     *err += "; recovering";
257     return true;
258   }
259
260   fclose(f);
261
262   // Rebuild the log if there are too many dead records.
263   int kMinCompactionEntryCount = 1000;
264   int kCompactionRatio = 3;
265   if (total_dep_record_count > kMinCompactionEntryCount &&
266       total_dep_record_count > unique_dep_record_count * kCompactionRatio) {
267     needs_recompaction_ = true;
268   }
269
270   return true;
271 }
272
273 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
274   // Abort if the node has no id (never referenced in the deps) or if
275   // there's no deps recorded for the node.
276   if (node->id() < 0 || node->id() >= (int)deps_.size())
277     return NULL;
278   return deps_[node->id()];
279 }
280
281 bool DepsLog::Recompact(const string& path, string* err) {
282   METRIC_RECORD(".ninja_deps recompact");
283   printf("Recompacting deps...\n");
284
285   string temp_path = path + ".recompact";
286
287   // OpenForWrite() opens for append.  Make sure it's not appending to a
288   // left-over file from a previous recompaction attempt that crashed somehow.
289   unlink(temp_path.c_str());
290
291   DepsLog new_log;
292   if (!new_log.OpenForWrite(temp_path, err))
293     return false;
294
295   // Clear all known ids so that new ones can be reassigned.  The new indices
296   // will refer to the ordering in new_log, not in the current log.
297   for (vector<Node*>::iterator i = nodes_.begin(); i != nodes_.end(); ++i)
298     (*i)->set_id(-1);
299   
300   // Write out all deps again.
301   for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
302     Deps* deps = deps_[old_id];
303     if (!deps) continue;  // If nodes_[old_id] is a leaf, it has no deps.
304
305     if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
306                             deps->node_count, deps->nodes)) {
307       new_log.Close();
308       return false;
309     }
310   }
311
312   new_log.Close();
313
314   // All nodes now have ids that refer to new_log, so steal its data.
315   deps_.swap(new_log.deps_);
316   nodes_.swap(new_log.nodes_);
317
318   if (unlink(path.c_str()) < 0) {
319     *err = strerror(errno);
320     return false;
321   }
322
323   if (rename(temp_path.c_str(), path.c_str()) < 0) {
324     *err = strerror(errno);
325     return false;
326   }
327
328   return true;
329 }
330
331 bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
332   if (out_id >= (int)deps_.size())
333     deps_.resize(out_id + 1);
334
335   bool delete_old = deps_[out_id] != NULL;
336   if (delete_old)
337     delete deps_[out_id];
338   deps_[out_id] = deps;
339   return delete_old;
340 }
341
342 bool DepsLog::RecordId(Node* node) {
343   size_t size = node->path().size();
344   if (size > kMaxRecordSize) {
345     errno = ERANGE;
346     return false;
347   }
348   uint16_t size16 = (uint16_t)size;
349   if (fwrite(&size16, 2, 1, file_) < 1)
350     return false;
351   if (fwrite(node->path().data(), node->path().size(), 1, file_) < 1) {
352     assert(node->path().size() > 0);
353     return false;
354   }
355   if (fflush(file_) != 0)
356     return false;
357
358   node->set_id(nodes_.size());
359   nodes_.push_back(node);
360
361   return true;
362 }