don't count eof as truncated
[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 DepsLog::~DepsLog() {
36   Close();
37 }
38
39 bool DepsLog::OpenForWrite(const string& path, string* err) {
40   file_ = fopen(path.c_str(), "ab");
41   if (!file_) {
42     *err = strerror(errno);
43     return false;
44   }
45   SetCloseOnExec(fileno(file_));
46
47   // Opening a file in append mode doesn't set the file pointer to the file's
48   // end on Windows. Do that explicitly.
49   fseek(file_, 0, SEEK_END);
50
51   if (ftell(file_) == 0) {
52     if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
53       *err = strerror(errno);
54       return false;
55     }
56     if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
57       *err = strerror(errno);
58       return false;
59     }
60   }
61
62   return true;
63 }
64
65 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
66                          const vector<Node*>& nodes) {
67   return RecordDeps(node, mtime, nodes.size(),
68                     nodes.empty() ? NULL : (Node**)&nodes.front());
69 }
70
71 bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
72                          int node_count, Node** nodes) {
73   // Track whether there's any new data to be recorded.
74   bool made_change = false;
75
76   // Assign ids to all nodes that are missing one.
77   if (node->id() < 0) {
78     RecordId(node);
79     made_change = true;
80   }
81   for (int i = 0; i < node_count; ++i) {
82     if (nodes[i]->id() < 0) {
83       RecordId(nodes[i]);
84       made_change = true;
85     }
86   }
87
88   // See if the new data is different than the existing data, if any.
89   if (!made_change) {
90     Deps* deps = GetDeps(node);
91     if (!deps ||
92         deps->mtime != mtime ||
93         deps->node_count != node_count) {
94       made_change = true;
95     } else {
96       for (int i = 0; i < node_count; ++i) {
97         if (deps->nodes[i] != nodes[i]) {
98           made_change = true;
99           break;
100         }
101       }
102     }
103   }
104
105   // Don't write anything if there's no new info.
106   if (!made_change)
107     return true;
108
109   uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
110   size |= 0x8000;  // Deps record: set high bit.
111   fwrite(&size, 2, 1, file_);
112   int id = node->id();
113   fwrite(&id, 4, 1, file_);
114   int timestamp = mtime;
115   fwrite(&timestamp, 4, 1, file_);
116   for (int i = 0; i < node_count; ++i) {
117     id = nodes[i]->id();
118     fwrite(&id, 4, 1, file_);
119   }
120
121   return true;
122 }
123
124 void DepsLog::Close() {
125   if (file_)
126     fclose(file_);
127   file_ = NULL;
128 }
129
130 bool DepsLog::Load(const string& path, State* state, string* err) {
131   METRIC_RECORD(".ninja_deps load");
132   char buf[32 << 10];
133   FILE* f = fopen(path.c_str(), "rb");
134   if (!f) {
135     if (errno == ENOENT)
136       return true;
137     *err = strerror(errno);
138     return false;
139   }
140
141   bool valid_header = true;
142   int version = 0;
143   if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
144     valid_header = false;
145   if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
146       version != kCurrentVersion) {
147     *err = "bad deps log signature or version; starting over";
148     fclose(f);
149     unlink(path.c_str());
150     // Don't report this as a failure.  An empty deps log will cause
151     // us to rebuild the outputs anyway.
152     return true;
153   }
154
155   long offset;
156   bool read_failed = false;
157   for (;;) {
158     offset = ftell(f);
159
160     uint16_t size;
161     if (fread(&size, 2, 1, f) < 1) {
162       if (!feof(f))
163         read_failed = true;
164       break;
165     }
166     bool is_deps = (size >> 15) != 0;
167     size = size & 0x7FFF;
168
169     if (fread(buf, size, 1, f) < 1) {
170       read_failed = true;
171       break;
172     }
173
174     if (is_deps) {
175       assert(size % 4 == 0);
176       int* deps_data = reinterpret_cast<int*>(buf);
177       int out_id = deps_data[0];
178       int mtime = deps_data[1];
179       deps_data += 2;
180       int deps_count = (size / 4) - 2;
181
182       Deps* deps = new Deps;
183       deps->mtime = mtime;
184       deps->node_count = deps_count;
185       deps->nodes = new Node*[deps_count];
186       for (int i = 0; i < deps_count; ++i) {
187         assert(deps_data[i] < (int)nodes_.size());
188         assert(nodes_[deps_data[i]]);
189         deps->nodes[i] = nodes_[deps_data[i]];
190       }
191
192       if (out_id >= (int)deps_.size())
193         deps_.resize(out_id + 1);
194       if (deps_[out_id]) {
195         ++dead_record_count_;
196         delete deps_[out_id];
197       }
198       deps_[out_id] = deps;
199     } else {
200       StringPiece path(buf, size);
201       Node* node = state->GetNode(path);
202       assert(node->id() < 0);
203       node->set_id(nodes_.size());
204       nodes_.push_back(node);
205     }
206   }
207
208   if (read_failed) {
209     // An error occurred while loading; try to recover by truncating the
210     // file to the last fully-read record.
211     if (ferror(f)) {
212       *err = strerror(ferror(f));
213     } else {
214       *err = "premature end of file";
215     }
216     fclose(f);
217
218     if (truncate(path.c_str(), offset) < 0) {
219       *err = strerror(errno);
220       return false;
221     }
222
223     // The truncate succeeded; we'll just report the load error as a
224     // warning because the build can proceed.
225     *err += "; recovering";
226     return true;
227   }
228
229   fclose(f);
230
231   return true;
232 }
233
234 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
235   // Abort if the node has no id (never referenced in the deps) or if
236   // there's no deps recorded for the node.
237   if (node->id() < 0 || node->id() >= (int)deps_.size())
238     return NULL;
239   return deps_[node->id()];
240 }
241
242 bool DepsLog::Recompact(const string& path, string* err) {
243   METRIC_RECORD(".ninja_deps recompact");
244   printf("Recompacting deps...\n");
245
246   string temp_path = path + ".recompact";
247   DepsLog new_log;
248   if (!new_log.OpenForWrite(temp_path, err))
249     return false;
250
251   // Clear all known ids so that new ones can be reassigned.
252   for (vector<Node*>::iterator i = nodes_.begin();
253        i != nodes_.end(); ++i) {
254     (*i)->set_id(-1);
255   }
256
257   // Write out all deps again.
258   for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
259     Deps* deps = deps_[old_id];
260     if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
261                             deps->node_count, deps->nodes)) {
262       new_log.Close();
263       return false;
264     }
265   }
266
267   new_log.Close();
268
269   if (unlink(path.c_str()) < 0) {
270     *err = strerror(errno);
271     return false;
272   }
273
274   if (rename(temp_path.c_str(), path.c_str()) < 0) {
275     *err = strerror(errno);
276     return false;
277   }
278
279   return true;
280 }
281
282 bool DepsLog::RecordId(Node* node) {
283   uint16_t size = (uint16_t)node->path().size();
284   fwrite(&size, 2, 1, file_);
285   fwrite(node->path().data(), node->path().size(), 1, file_);
286
287   node->set_id(nodes_.size());
288   nodes_.push_back(node);
289
290   return true;
291 }