Let DepsLog::RecordDeps() update its in-memory representation.
[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   // Update on-disk representation.
110   uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
111   size |= 0x8000;  // Deps record: set high bit.
112   fwrite(&size, 2, 1, file_);
113   int id = node->id();
114   fwrite(&id, 4, 1, file_);
115   int timestamp = mtime;
116   fwrite(&timestamp, 4, 1, file_);
117   for (int i = 0; i < node_count; ++i) {
118     id = nodes[i]->id();
119     fwrite(&id, 4, 1, file_);
120   }
121
122   // Update in-memory representation.
123   Deps* deps = new Deps(mtime, node_count);
124   for (int i = 0; i < node_count; ++i)
125     deps->nodes[i] = nodes[i];
126   UpdateDeps(node->id(), deps);
127
128   return true;
129 }
130
131 void DepsLog::Close() {
132   if (file_)
133     fclose(file_);
134   file_ = NULL;
135 }
136
137 bool DepsLog::Load(const string& path, State* state, string* err) {
138   METRIC_RECORD(".ninja_deps load");
139   char buf[32 << 10];
140   FILE* f = fopen(path.c_str(), "rb");
141   if (!f) {
142     if (errno == ENOENT)
143       return true;
144     *err = strerror(errno);
145     return false;
146   }
147
148   bool valid_header = true;
149   int version = 0;
150   if (!fgets(buf, sizeof(buf), f) || fread(&version, 4, 1, f) < 1)
151     valid_header = false;
152   if (!valid_header || strcmp(buf, kFileSignature) != 0 ||
153       version != kCurrentVersion) {
154     *err = "bad deps log signature or version; starting over";
155     fclose(f);
156     unlink(path.c_str());
157     // Don't report this as a failure.  An empty deps log will cause
158     // us to rebuild the outputs anyway.
159     return true;
160   }
161
162   long offset;
163   bool read_failed = false;
164   for (;;) {
165     offset = ftell(f);
166
167     uint16_t size;
168     if (fread(&size, 2, 1, f) < 1) {
169       if (!feof(f))
170         read_failed = true;
171       break;
172     }
173     bool is_deps = (size >> 15) != 0;
174     size = size & 0x7FFF;
175
176     if (fread(buf, size, 1, f) < 1) {
177       read_failed = true;
178       break;
179     }
180
181     if (is_deps) {
182       assert(size % 4 == 0);
183       int* deps_data = reinterpret_cast<int*>(buf);
184       int out_id = deps_data[0];
185       int mtime = deps_data[1];
186       deps_data += 2;
187       int deps_count = (size / 4) - 2;
188
189       Deps* deps = new Deps(mtime, deps_count);
190       for (int i = 0; i < deps_count; ++i) {
191         assert(deps_data[i] < (int)nodes_.size());
192         assert(nodes_[deps_data[i]]);
193         deps->nodes[i] = nodes_[deps_data[i]];
194       }
195
196       if (UpdateDeps(out_id, deps))
197         ++dead_record_count_;
198     } else {
199       StringPiece path(buf, size);
200       Node* node = state->GetNode(path);
201       assert(node->id() < 0);
202       node->set_id(nodes_.size());
203       nodes_.push_back(node);
204     }
205   }
206
207   if (read_failed) {
208     // An error occurred while loading; try to recover by truncating the
209     // file to the last fully-read record.
210     if (ferror(f)) {
211       *err = strerror(ferror(f));
212     } else {
213       *err = "premature end of file";
214     }
215     fclose(f);
216
217     if (!Truncate(path.c_str(), offset, err))
218       return false;
219
220     // The truncate succeeded; we'll just report the load error as a
221     // warning because the build can proceed.
222     *err += "; recovering";
223     return true;
224   }
225
226   fclose(f);
227
228   return true;
229 }
230
231 DepsLog::Deps* DepsLog::GetDeps(Node* node) {
232   // Abort if the node has no id (never referenced in the deps) or if
233   // there's no deps recorded for the node.
234   if (node->id() < 0 || node->id() >= (int)deps_.size())
235     return NULL;
236   return deps_[node->id()];
237 }
238
239 bool DepsLog::Recompact(const string& path, string* err) {
240   METRIC_RECORD(".ninja_deps recompact");
241   printf("Recompacting deps...\n");
242
243   string temp_path = path + ".recompact";
244
245   // OpenForWrite() opens for append.  Make sure it's not appending to a
246   // left-over file from a previous recompaction attempt that crashed somehow.
247   unlink(temp_path.c_str());
248
249   DepsLog new_log;
250   if (!new_log.OpenForWrite(temp_path, err))
251     return false;
252
253   // Clear all known ids so that new ones can be reassigned.
254   for (vector<Node*>::iterator i = nodes_.begin();
255        i != nodes_.end(); ++i) {
256     (*i)->set_id(-1);
257   }
258
259   // Write out all deps again.
260   for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
261     Deps* deps = deps_[old_id];
262     if (!deps) continue;  // If nodes_[old_id] is a leaf, it has no deps.
263
264     if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
265                             deps->node_count, deps->nodes)) {
266       new_log.Close();
267       return false;
268     }
269   }
270
271   new_log.Close();
272
273   if (unlink(path.c_str()) < 0) {
274     *err = strerror(errno);
275     return false;
276   }
277
278   if (rename(temp_path.c_str(), path.c_str()) < 0) {
279     *err = strerror(errno);
280     return false;
281   }
282
283   return true;
284 }
285
286 bool DepsLog::UpdateDeps(int out_id, Deps* deps) {
287   if (out_id >= (int)deps_.size())
288     deps_.resize(out_id + 1);
289
290   bool delete_old = deps_[out_id] != NULL;
291   if (delete_old)
292     delete deps_[out_id];
293   deps_[out_id] = deps;
294   return delete_old;
295 }
296
297 bool DepsLog::RecordId(Node* node) {
298   uint16_t size = (uint16_t)node->path().size();
299   fwrite(&size, 2, 1, file_);
300   fwrite(node->path().data(), node->path().size(), 1, file_);
301
302   node->set_id(nodes_.size());
303   nodes_.push_back(node);
304
305   return true;
306 }