summaryrefslogtreecommitdiffstats
path: root/startupcache/test/TestStartupCache.cpp
blob: a16c2de727322a87c8495fdbcb15c629554f4a8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/* -*-  Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TestHarness.h"

#include "nsThreadUtils.h"
#include "nsIClassInfo.h"
#include "nsIOutputStream.h"
#include "nsIObserver.h"
#include "nsISerializable.h"
#include "nsISupports.h"
#include "nsIStartupCache.h"
#include "nsIStringStream.h"
#include "nsIStorageStream.h"
#include "nsIObjectInputStream.h"
#include "nsIObjectOutputStream.h"
#include "nsIURI.h"
#include "nsStringAPI.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsIXPConnect.h"
#include "prio.h"
#include "mozilla/Maybe.h"
#include "mozilla/UniquePtr.h"

using namespace JS;

namespace mozilla {
namespace scache {

NS_IMPORT nsresult
NewObjectInputStreamFromBuffer(UniquePtr<char[]> buffer, uint32_t len, 
                               nsIObjectInputStream** stream);

// We can't retrieve the wrapped stream from the objectOutputStream later,
// so we return it here.
NS_IMPORT nsresult
NewObjectOutputWrappedStorageStream(nsIObjectOutputStream **wrapperStream,
                                    nsIStorageStream** stream);

NS_IMPORT nsresult
NewBufferFromStorageStream(nsIStorageStream *storageStream, 
                           UniquePtr<char[]>* buffer, uint32_t* len);
} // namespace scache
} // namespace mozilla

using namespace mozilla::scache;
using mozilla::UniquePtr;

#define NS_ENSURE_STR_MATCH(str1, str2, testname)  \
PR_BEGIN_MACRO                                     \
if (0 != strcmp(str1, str2)) {                     \
  fail("failed " testname);                        \
  return NS_ERROR_FAILURE;                         \
}                                                  \
passed("passed " testname);                        \
PR_END_MACRO

nsresult
WaitForStartupTimer() {
  nsresult rv;
  nsCOMPtr<nsIStartupCache> sc
    = do_GetService("@mozilla.org/startupcache/cache;1");
  PR_Sleep(10 * PR_TicksPerSecond());
  
  bool complete;
  while (true) {
    
    NS_ProcessPendingEvents(nullptr);
    rv = sc->StartupWriteComplete(&complete);
    if (NS_FAILED(rv) || complete)
      break;
    PR_Sleep(1 * PR_TicksPerSecond());
  }
  return rv;
}

nsresult
TestStartupWriteRead() {
  nsresult rv;
  nsCOMPtr<nsIStartupCache> sc
    = do_GetService("@mozilla.org/startupcache/cache;1", &rv);
  if (!sc) {
    fail("didn't get a pointer...");
    return NS_ERROR_FAILURE;
  } else {
    passed("got a pointer?");
  }
  sc->InvalidateCache();
  
  const char* buf = "Market opportunities for BeardBook";
  const char* id = "id";
  UniquePtr<char[]> outbuf;  
  uint32_t len;
  
  rv = sc->PutBuffer(id, buf, strlen(buf) + 1);
  NS_ENSURE_SUCCESS(rv, rv);
  
  rv = sc->GetBuffer(id, &outbuf, &len);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_STR_MATCH(buf, outbuf.get(), "pre-write read");

  rv = sc->ResetStartupWriteTimer();
  rv = WaitForStartupTimer();
  NS_ENSURE_SUCCESS(rv, rv);
  
  rv = sc->GetBuffer(id, &outbuf, &len);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_STR_MATCH(buf, outbuf.get(), "simple write/read");

  return NS_OK;
}

nsresult
TestWriteInvalidateRead() {
  nsresult rv;
  const char* buf = "BeardBook competitive analysis";
  const char* id = "id";
  UniquePtr<char[]> outbuf;
  uint32_t len;
  nsCOMPtr<nsIStartupCache> sc
    = do_GetService("@mozilla.org/startupcache/cache;1", &rv);
  sc->InvalidateCache();

  rv = sc->PutBuffer(id, buf, strlen(buf) + 1);
  NS_ENSURE_SUCCESS(rv, rv);

  sc->InvalidateCache();

  rv = sc->GetBuffer(id, &outbuf, &len);
  if (rv == NS_ERROR_NOT_AVAILABLE) {
    passed("buffer not available after invalidate");
  } else if (NS_SUCCEEDED(rv)) {
    fail("GetBuffer succeeded unexpectedly after invalidate");
    return NS_ERROR_UNEXPECTED;
  } else {
    fail("GetBuffer gave an unexpected failure, expected NOT_AVAILABLE");
    return rv;
  }

  sc->InvalidateCache();
  return NS_OK;
}

nsresult
TestWriteObject() {
  nsresult rv;

  nsCOMPtr<nsIURI> obj
    = do_CreateInstance("@mozilla.org/network/simple-uri;1");
  if (!obj) {
    fail("did not create object in test write object");
    return NS_ERROR_UNEXPECTED;
  }
  NS_NAMED_LITERAL_CSTRING(spec, "http://www.mozilla.org");
  rv = obj->SetSpec(spec);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIStartupCache> sc = do_GetService("@mozilla.org/startupcache/cache;1", &rv);

  sc->InvalidateCache();
  
  // Create an object stream. Usually this is done with
  // NewObjectOutputWrappedStorageStream, but that uses
  // StartupCache::GetSingleton in debug builds, and we
  // don't have access to that here. Obviously.
  const char* id = "id";
  nsCOMPtr<nsIStorageStream> storageStream
    = do_CreateInstance("@mozilla.org/storagestream;1");
  NS_ENSURE_ARG_POINTER(storageStream);
  
  rv = storageStream->Init(256, (uint32_t) -1);
  NS_ENSURE_SUCCESS(rv, rv);
  
  nsCOMPtr<nsIObjectOutputStream> objectOutput
    = do_CreateInstance("@mozilla.org/binaryoutputstream;1");
  if (!objectOutput)
    return NS_ERROR_OUT_OF_MEMORY;
  
  nsCOMPtr<nsIOutputStream> outputStream
    = do_QueryInterface(storageStream);
  
  rv = objectOutput->SetOutputStream(outputStream);

  if (NS_FAILED(rv)) {
    fail("failed to create output stream");
    return rv;
  }
  nsCOMPtr<nsISupports> objQI(do_QueryInterface(obj));
  rv = objectOutput->WriteObject(objQI, true);
  if (NS_FAILED(rv)) {
    fail("failed to write object");
    return rv;
  }

  UniquePtr<char[]> buf;
  uint32_t len;
  NewBufferFromStorageStream(storageStream, &buf, &len);

  // Since this is a post-startup write, it should be written and
  // available.
  rv = sc->PutBuffer(id, buf.get(), len);
  if (NS_FAILED(rv)) {
    fail("failed to insert input stream");
    return rv;
  }
    
  UniquePtr<char[]> buf2;
  uint32_t len2;
  nsCOMPtr<nsIObjectInputStream> objectInput;
  rv = sc->GetBuffer(id, &buf2, &len2);
  if (NS_FAILED(rv)) {
    fail("failed to retrieve buffer");
    return rv;
  }

  rv = NewObjectInputStreamFromBuffer(Move(buf2), len2,
                                      getter_AddRefs(objectInput));
  if (NS_FAILED(rv)) {
    fail("failed to created input stream");
    return rv;
  }  

  nsCOMPtr<nsISupports> deserialized;
  rv = objectInput->ReadObject(true, getter_AddRefs(deserialized));
  if (NS_FAILED(rv)) {
    fail("failed to read object");
    return rv;
  }
  
  bool match = false;
  nsCOMPtr<nsIURI> uri(do_QueryInterface(deserialized));
  if (uri) {
    nsCString outSpec;
    rv = uri->GetSpec(outSpec);
    if (NS_FAILED(rv)) {
      fail("failed to get spec");
      return rv;
    }
    match = outSpec.Equals(spec);
  }
  if (!match) {
    fail("deserialized object has incorrect information");
    return rv;
  }
  
  passed("write object");
  return NS_OK;
}

nsresult
LockCacheFile(bool protect, nsIFile* profileDir) {
  NS_ENSURE_ARG(profileDir);

  nsCOMPtr<nsIFile> startupCache;
  profileDir->Clone(getter_AddRefs(startupCache));
  NS_ENSURE_STATE(startupCache);
  startupCache->AppendNative(NS_LITERAL_CSTRING("startupCache"));

  nsresult rv;
#ifndef XP_WIN
  static uint32_t oldPermissions;
#else
  static PRFileDesc* fd = nullptr;
#endif

  // To prevent deletion of the startupcache file, we change the containing
  // directory's permissions on Linux/Mac, and hold the file open on Windows
  if (protect) {
#ifndef XP_WIN
    rv = startupCache->GetPermissions(&oldPermissions);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = startupCache->SetPermissions(0555);
    NS_ENSURE_SUCCESS(rv, rv);
#else
    // Filename logic from StartupCache.cpp
    #ifdef IS_BIG_ENDIAN
    #define SC_ENDIAN "big"
    #else
    #define SC_ENDIAN "little"
    #endif

    #if PR_BYTES_PER_WORD == 4
    #define SC_WORDSIZE "4"
    #else
    #define SC_WORDSIZE "8"
    #endif
    char sStartupCacheName[] = "startupCache." SC_WORDSIZE "." SC_ENDIAN;
    startupCache->AppendNative(NS_LITERAL_CSTRING(sStartupCacheName));

    rv = startupCache->OpenNSPRFileDesc(PR_RDONLY, 0, &fd);
    NS_ENSURE_SUCCESS(rv, rv);
#endif
  } else {
#ifndef XP_WIN
    rv = startupCache->SetPermissions(oldPermissions);
    NS_ENSURE_SUCCESS(rv, rv);
#else
   PR_Close(fd);
#endif
  }

  return NS_OK;
}

nsresult
TestIgnoreDiskCache(nsIFile* profileDir) {
  nsresult rv;
  nsCOMPtr<nsIStartupCache> sc
    = do_GetService("@mozilla.org/startupcache/cache;1", &rv);
  sc->InvalidateCache();
  
  const char* buf = "Get a Beardbook app for your smartphone";
  const char* id = "id";
  UniquePtr<char[]> outbuf;
  uint32_t len;
  
  rv = sc->PutBuffer(id, buf, strlen(buf) + 1);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = sc->ResetStartupWriteTimer();
  rv = WaitForStartupTimer();
  NS_ENSURE_SUCCESS(rv, rv);

  // Prevent StartupCache::InvalidateCache from deleting the disk file
  rv = LockCacheFile(true, profileDir);
  NS_ENSURE_SUCCESS(rv, rv);

  sc->IgnoreDiskCache();

  rv = sc->GetBuffer(id, &outbuf, &len);

  nsresult r = LockCacheFile(false, profileDir);
  NS_ENSURE_SUCCESS(r, r);

  if (rv == NS_ERROR_NOT_AVAILABLE) {
    passed("buffer not available after ignoring disk cache");
  } else if (NS_SUCCEEDED(rv)) {
    fail("GetBuffer succeeded unexpectedly after ignoring disk cache");
    return NS_ERROR_UNEXPECTED;
  } else {
    fail("GetBuffer gave an unexpected failure, expected NOT_AVAILABLE");
    return rv;
  }

  sc->InvalidateCache();
  return NS_OK;
}

nsresult
TestEarlyShutdown() {
  nsresult rv;
  nsCOMPtr<nsIStartupCache> sc
    = do_GetService("@mozilla.org/startupcache/cache;1", &rv);
  sc->InvalidateCache();

  const char* buf = "Find your soul beardmate on BeardBook";
  const char* id = "id";
  uint32_t len;
  UniquePtr<char[]> outbuf;
  
  sc->ResetStartupWriteTimer();
  rv = sc->PutBuffer(id, buf, strlen(buf) + 1);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIObserver> obs;
  sc->GetObserver(getter_AddRefs(obs));
  obs->Observe(nullptr, "xpcom-shutdown", nullptr);
  rv = WaitForStartupTimer();
  NS_ENSURE_SUCCESS(rv, rv);
  
  rv = sc->GetBuffer(id, &outbuf, &len);

  if (NS_SUCCEEDED(rv)) {
    passed("GetBuffer succeeded after early shutdown");
  } else {
    fail("GetBuffer failed after early shutdown");
    return rv;
  }

  const char* other_id = "other_id";
  rv = sc->PutBuffer(other_id, buf, strlen(buf) + 1);

  if (rv == NS_ERROR_NOT_AVAILABLE) {
    passed("PutBuffer not available after early shutdown");
  } else if (NS_SUCCEEDED(rv)) {
    fail("PutBuffer succeeded unexpectedly after early shutdown");
    return NS_ERROR_UNEXPECTED;
  } else {
    fail("PutBuffer gave an unexpected failure, expected NOT_AVAILABLE");
    return rv;
  }
 
  return NS_OK;
}

int main(int argc, char** argv)
{
  ScopedXPCOM xpcom("Startup Cache");
  if (xpcom.failed())
    return 1;

  nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
  if (!prefs) {
    fail("prefs");
    return 1;
  }
  prefs->SetIntPref("hangmonitor.timeout", 0);

  int rv = 0;
  nsresult scrv;

  // Register TestStartupCacheTelemetry
  nsCOMPtr<nsIFile> manifest;
  scrv = NS_GetSpecialDirectory(NS_GRE_DIR,
                                getter_AddRefs(manifest));
  if (NS_FAILED(scrv)) {
    fail("NS_XPCOM_CURRENT_PROCESS_DIR");
    return 1;
  }

#ifdef XP_MACOSX
  nsCOMPtr<nsIFile> tempManifest;
  manifest->Clone(getter_AddRefs(tempManifest));
  manifest->AppendNative(
    NS_LITERAL_CSTRING("TestStartupCacheTelemetry.manifest"));
  bool exists;
  manifest->Exists(&exists);
  if (!exists) {
    // Workaround for bug 1080338 in mozharness.
    manifest = tempManifest.forget();
    manifest->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS"));
    manifest->AppendNative(
      NS_LITERAL_CSTRING("TestStartupCacheTelemetry.manifest"));
  }
#else
  manifest->AppendNative(
    NS_LITERAL_CSTRING("TestStartupCacheTelemetry.manifest"));
#endif

  XRE_AddManifestLocation(NS_APP_LOCATION, manifest);

  nsCOMPtr<nsIObserver> telemetryThing =
    do_GetService("@mozilla.org/testing/startup-cache-telemetry.js");
  if (!telemetryThing) {
    fail("telemetryThing");
    return 1;
  }
  scrv = telemetryThing->Observe(nullptr, "save-initial", nullptr);
  if (NS_FAILED(scrv)) {
    fail("save-initial");
    rv = 1;
  }

  nsCOMPtr<nsIStartupCache> sc 
    = do_GetService("@mozilla.org/startupcache/cache;1", &scrv);
  if (NS_FAILED(scrv))
    rv = 1;
  else
    sc->RecordAgesAlways();
  if (NS_FAILED(TestStartupWriteRead()))
    rv = 1;
  if (NS_FAILED(TestWriteInvalidateRead()))
    rv = 1;
  if (NS_FAILED(TestWriteObject()))
    rv = 1;
  nsCOMPtr<nsIFile> profileDir = xpcom.GetProfileDirectory();
  if (NS_FAILED(TestIgnoreDiskCache(profileDir)))
    rv = 1;
  if (NS_FAILED(TestEarlyShutdown()))
    rv = 1;

  scrv = telemetryThing->Observe(nullptr, "save-initial", nullptr);
  if (NS_FAILED(scrv)) {
    fail("check-final");
    rv = 1;
  }

  return rv;
}