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