コード例 #1
0
ファイル: TestCaching.cpp プロジェクト: luke-chang/gecko-1
void TestInvalidateExpiredCacheEntry()
{
  _PrefixArray array = { GeneratePrefix(CACHED_URL, 10),
                         GeneratePrefix(NEG_CACHE_EXPIRED_URL, 8),
                         GeneratePrefix(POS_CACHE_EXPIRED_URL, 5),
                         GeneratePrefix(BOTH_CACHE_EXPIRED_URL, 4)
                       };
  UniquePtr<T> cache = SetupLookupCache<T>(array);

  SetupCacheEntry(cache.get(), CACHED_URL, false, false);
  SetupCacheEntry(cache.get(), NEG_CACHE_EXPIRED_URL, true, false);
  SetupCacheEntry(cache.get(), POS_CACHE_EXPIRED_URL, false, true);
  SetupCacheEntry(cache.get(), BOTH_CACHE_EXPIRED_URL, true, true);

  // Before invalidate
  TestCache<T>(CACHED_URL, true, true, true, cache.get());
  TestCache<T>(NEG_CACHE_EXPIRED_URL, true, true, true, cache.get());
  TestCache<T>(POS_CACHE_EXPIRED_URL, true, false, true, cache.get());
  TestCache<T>(BOTH_CACHE_EXPIRED_URL, true, false, true, cache.get());

  // Call InvalidateExpiredCacheEntry to remove cache entries whose negative cache
  // time is expired
  cache->InvalidateExpiredCacheEntries();

  // After invalidate, NEG_CACHE_EXPIRED_URL & BOTH_CACHE_EXPIRED_URL should
  // not be found in cache.
  TestCache<T>(NEG_CACHE_EXPIRED_URL, true, false, false, cache.get());
  TestCache<T>(BOTH_CACHE_EXPIRED_URL, true, false, false, cache.get());

  // Other entries should remain the same result.
  TestCache<T>(CACHED_URL, true, true, true, cache.get());
  TestCache<T>(POS_CACHE_EXPIRED_URL, true, false, true, cache.get());
}
コード例 #2
0
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;
}
コード例 #3
0
NS_IMETHODIMP
nsBinaryInputStream::ReadArrayBuffer(uint32_t aLength,
                                     JS::Handle<JS::Value> aBuffer,
                                     JSContext* aCx, uint32_t* aReadLength)
{
  if (!aBuffer.isObject()) {
    return NS_ERROR_FAILURE;
  }
  JS::RootedObject buffer(aCx, &aBuffer.toObject());
  if (!JS_IsArrayBufferObject(buffer)) {
    return NS_ERROR_FAILURE;
  }

  uint32_t bufferLength = JS_GetArrayBufferByteLength(buffer);
  if (bufferLength < aLength) {
    return NS_ERROR_FAILURE;
  }

  uint32_t bufSize = std::min<uint32_t>(aLength, 4096);
  UniquePtr<char[]> buf = MakeUnique<char[]>(bufSize);

  uint32_t pos = 0;
  *aReadLength = 0;
  do {
    // Read data into temporary buffer.
    uint32_t bytesRead;
    uint32_t amount = std::min(aLength - pos, bufSize);
    nsresult rv = Read(buf.get(), amount, &bytesRead);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
    MOZ_ASSERT(bytesRead <= amount);

    if (bytesRead == 0) {
      break;
    }

    // Copy data into actual buffer.

    JS::AutoCheckCannotGC nogc;
    bool isShared;
    if (bufferLength != JS_GetArrayBufferByteLength(buffer)) {
      return NS_ERROR_FAILURE;
    }

    char* data = reinterpret_cast<char*>(JS_GetArrayBufferData(buffer, &isShared, nogc));
    MOZ_ASSERT(!isShared);      // Implied by JS_GetArrayBufferData()
    if (!data) {
      return NS_ERROR_FAILURE;
    }

    *aReadLength += bytesRead;
    PodCopy(data + pos, buf.get(), bytesRead);

    pos += bytesRead;
  } while (pos < aLength);

  return NS_OK;
}
コード例 #4
0
ファイル: fe_xyz_boundary.C プロジェクト: friedmud/libmesh
void FEXYZ<Dim>::reinit(const Elem * elem,
                        const unsigned int s,
                        const Real,
                        const std::vector<Point> * const pts,
                        const std::vector<Real> * const weights)
{
  libmesh_assert(elem);
  libmesh_assert (this->qrule != libmesh_nullptr || pts != libmesh_nullptr);
  // We don't do this for 1D elements!
  libmesh_assert_not_equal_to (Dim, 1);

  // Build the side of interest
  const UniquePtr<const Elem> side(elem->build_side_ptr(s));

  // Initialize the shape functions at the user-specified
  // points
  if (pts != libmesh_nullptr)
    {
      // We can't get away without recomputing shape functions next
      // time
      this->shapes_on_quadrature = false;

      // Set the element type
      this->elem_type = elem->type();

      // Initialize the face shape functions
      this->_fe_map->template init_face_shape_functions<Dim>(*pts,  side.get());
      if (weights != libmesh_nullptr)
        {
          this->compute_face_values (elem, side.get(), *weights);
        }
      else
        {
          std::vector<Real> dummy_weights (pts->size(), 1.);
          // Compute data on the face for integration
          this->compute_face_values (elem, side.get(), dummy_weights);
        }
    }
  else
    {
      // initialize quadrature rule
      this->qrule->init(side->type(), elem->p_level());

      {
        // Set the element type
        this->elem_type = elem->type();

        // Initialize the face shape functions
        this->_fe_map->template init_face_shape_functions<Dim>(this->qrule->get_points(),  side.get());
      }
      // We can't get away without recomputing shape functions next
      // time
      this->shapes_on_quadrature = false;
      // Compute data on the face for integration
      this->compute_face_values (elem, side.get(), this->qrule->get_weights());
    }
}
コード例 #5
0
void
nsSplitterFrameInner::AdjustChildren(nsPresContext* aPresContext)
{
  EnsureOrient();
  bool isHorizontal = !mOuter->IsHorizontal();

  AdjustChildren(aPresContext, mChildInfosBefore.get(),
                 mChildInfosBeforeCount, isHorizontal);
  AdjustChildren(aPresContext, mChildInfosAfter.get(),
                 mChildInfosAfterCount, isHorizontal);
}
コード例 #6
0
ファイル: Ril.cpp プロジェクト: MekliCZ/positron
void
RilConsumer::ReceiveSocketData(JSContext* aCx,
                               int aIndex,
                               UniquePtr<UnixSocketBuffer>& aBuffer)
{
  Receive(aCx, (uint32_t)aIndex, aBuffer.get());
}
コード例 #7
0
ファイル: Sandbox.cpp プロジェクト: paulmadore/luckyde
// Common code for sandbox startup.
static void
SetCurrentProcessSandbox(UniquePtr<sandbox::bpf_dsl::Policy> aPolicy)
{
  MOZ_ASSERT(gSandboxCrashFunc);

  // Note: PolicyCompiler borrows the policy and registry for its
  // lifetime, but does not take ownership of them.
  sandbox::bpf_dsl::PolicyCompiler compiler(aPolicy.get(),
                                            sandbox::Trap::Registry());
  auto program = compiler.Compile();
  if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
    sandbox::bpf_dsl::DumpBPF::PrintProgram(*program);
  }

  InstallSigSysHandler();

#ifdef MOZ_ASAN
  __sanitizer_sandbox_arguments asanArgs;
  asanArgs.coverage_sandboxed = 1;
  asanArgs.coverage_fd = -1;
  asanArgs.coverage_max_block_size = 0;
  __sanitizer_sandbox_on_notify(&asanArgs);
#endif

  // The syscall takes a C-style array, so copy the vector into one.
  UniquePtr<sock_filter[]> flatProgram(new sock_filter[program->size()]);
  for (auto i = program->begin(); i != program->end(); ++i) {
    flatProgram[i - program->begin()] = *i;
  }

  BroadcastSetThreadSandbox(Move(flatProgram), program->size());
}
コード例 #8
0
  bool read(char** ptr, uint32_t* lengthp) {
    if (fseek(fp_, 0, SEEK_END) == -1) {
      cc_.report(rmsg::file_read_error) << path_;
      return false;
    }

    long size = ftell(fp_);
    if (size == -1 || fseek(fp_, 0, SEEK_SET) == -1) {
      cc_.report(rmsg::file_read_error) << path_;
      return false;
    }

    if (size_t(size) > kMaxTotalSourceFileLength) {
      cc_.report(rmsg::file_too_large) << path_;
      return false;
    }

    UniquePtr<char[]> buffer = MakeUnique<char[]>(size + 1);
    if (!buffer) {
      cc_.reportFatal(rmsg::outofmemory);
      return false;
    }

    if (fread(buffer.get(), 1, size, fp_) != size_t(size)) {
      cc_.report(rmsg::file_read_error) << path_;
      return false;
    }

    *ptr = buffer.take();
    *lengthp = uint32_t(size);
    return true;
  }
コード例 #9
0
ファイル: AudioStream.cpp プロジェクト: ajkerrigan/gecko-dev
void
AudioStream::GetTimeStretched(AudioBufferWriter& aWriter)
{
    mMonitor.AssertCurrentThreadOwns();

    // We need to call the non-locking version, because we already have the lock.
    if (EnsureTimeStretcherInitializedUnlocked() != NS_OK) {
        return;
    }

    double playbackRate = static_cast<double>(mInRate) / mOutRate;
    uint32_t toPopFrames = ceil(aWriter.Available() * playbackRate);

    while (mTimeStretcher->numSamples() < aWriter.Available()) {
        UniquePtr<Chunk> c = mDataSource.PopFrames(toPopFrames);
        if (c->Frames() == 0) {
            break;
        }
        MOZ_ASSERT(c->Frames() <= toPopFrames);
        if (Downmix(c.get())) {
            mTimeStretcher->putSamples(c->Data(), c->Frames());
        } else {
            // Write silence if downmixing fails.
            nsAutoTArray<AudioDataValue, 1000> buf;
            buf.SetLength(mOutChannels * c->Frames());
            memset(buf.Elements(), 0, buf.Length() * sizeof(AudioDataValue));
            mTimeStretcher->putSamples(buf.Elements(), c->Frames());
        }
    }

    auto timeStretcher = mTimeStretcher;
    aWriter.Write([timeStretcher] (AudioDataValue* aPtr, uint32_t aFrames) {
        return timeStretcher->receiveSamples(aPtr, aFrames);
    }, aWriter.Available());
}
コード例 #10
0
nsresult
BluetoothSocket::Listen(const nsAString& aServiceName,
                        const BluetoothUuid& aServiceUuid,
                        BluetoothSocketType aType,
                        int aChannel,
                        bool aAuth, bool aEncrypt)
{
  UniquePtr<BluetoothUnixSocketConnector> connector =
    MakeUnique<BluetoothUnixSocketConnector>(BluetoothAddress::ANY(), aType,
                                             aChannel, aAuth, aEncrypt);

  nsresult rv = Listen(connector.get());
  if (NS_FAILED(rv)) {
    BluetoothAddress address;
    GetAddress(address);

    nsAutoString addressStr;
    AddressToString(address, addressStr);

    BT_LOGD("%s failed. Current connected device address: %s",
           __FUNCTION__, NS_ConvertUTF16toUTF8(addressStr).get());
    return rv;
  }
  Unused << connector.release();

  return NS_OK;
}
コード例 #11
0
ファイル: AudioStream.cpp プロジェクト: ajkerrigan/gecko-dev
void
AudioStream::GetUnprocessed(AudioBufferWriter& aWriter)
{
    mMonitor.AssertCurrentThreadOwns();

    // Flush the timestretcher pipeline, if we were playing using a playback rate
    // other than 1.0.
    if (mTimeStretcher && mTimeStretcher->numSamples()) {
        auto timeStretcher = mTimeStretcher;
        aWriter.Write([timeStretcher] (AudioDataValue* aPtr, uint32_t aFrames) {
            return timeStretcher->receiveSamples(aPtr, aFrames);
        }, aWriter.Available());

        // TODO: There might be still unprocessed samples in the stretcher.
        // We should either remove or flush them so they won't be in the output
        // next time we switch a playback rate other than 1.0.
        NS_WARN_IF(mTimeStretcher->numUnprocessedSamples() > 0);
    }

    while (aWriter.Available() > 0) {
        UniquePtr<Chunk> c = mDataSource.PopFrames(aWriter.Available());
        if (c->Frames() == 0) {
            break;
        }
        MOZ_ASSERT(c->Frames() <= aWriter.Available());
        if (Downmix(c.get())) {
            aWriter.Write(c->Data(), c->Frames());
        } else {
            // Write silence if downmixing fails.
            aWriter.WriteZeros(c->Frames());
        }
    }
}
コード例 #12
0
nsresult
nsXULPrototypeCache::FinishOutputStream(nsIURI* uri)
{
    nsresult rv;
    StartupCache* sc = StartupCache::GetSingleton();
    if (!sc)
        return NS_ERROR_NOT_AVAILABLE;

    nsCOMPtr<nsIStorageStream> storageStream;
    bool found = mOutputStreamTable.Get(uri, getter_AddRefs(storageStream));
    if (!found)
        return NS_ERROR_UNEXPECTED;
    nsCOMPtr<nsIOutputStream> outputStream
        = do_QueryInterface(storageStream);
    outputStream->Close();

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

    if (!mStartupCacheURITable.GetEntry(uri)) {
        nsAutoCString spec(kXULCachePrefix);
        rv = PathifyURI(uri, spec);
        if (NS_FAILED(rv))
            return NS_ERROR_NOT_AVAILABLE;
        rv = sc->PutBuffer(spec.get(), buf.get(), len);
        if (NS_SUCCEEDED(rv)) {
            mOutputStreamTable.Remove(uri);
            mStartupCacheURITable.PutEntry(uri);
        }
    }

    return rv;
}
コード例 #13
0
void VerifyProcTest(pid_t pid, pid_t tid, bool share_map,
                    bool (*ReadyFunc)(Backtrace*),
                    void (*VerifyFunc)(Backtrace*)) {
  pid_t ptrace_tid;
  if (tid < 0) {
    ptrace_tid = pid;
  } else {
    ptrace_tid = tid;
  }
  uint64_t start = NanoTime();
  bool verified = false;
  do {
    usleep(US_PER_MSEC);
    if (ptrace(PTRACE_ATTACH, ptrace_tid, 0, 0) == 0) {
      // Wait for the process to get to a stopping point.
      WaitForStop(ptrace_tid);

      UniquePtr<BacktraceMap> map;
      if (share_map) {
        map.reset(BacktraceMap::Create(pid));
      }
      UniquePtr<Backtrace> backtrace(Backtrace::Create(pid, tid, map.get()));
      ASSERT_TRUE(backtrace->Unwind(0));
      ASSERT_TRUE(backtrace.get() != NULL);
      if (ReadyFunc(backtrace.get())) {
        VerifyFunc(backtrace.get());
        verified = true;
      }

      ASSERT_TRUE(ptrace(PTRACE_DETACH, ptrace_tid, 0, 0) == 0);
    }
    // If 5 seconds have passed, then we are done.
  } while (!verified && (NanoTime() - start) <= 5 * NS_PER_SEC);
  ASSERT_TRUE(verified);
}
コード例 #14
0
 void InitData(const gfx::IntSize& aSize) {
   mData.mPicSize = aSize;
   mData.mYStride = aSize.width;
   mData.mYSize = aSize;
   mData.mCbCrStride = aSize.width / 2;
   mData.mCbCrSize = gfx::IntSize(aSize.width / 2, aSize.height / 2);
   size_t bufferSize = mData.mYStride * mData.mYSize.height +
                       mData.mCbCrStride * mData.mCbCrSize.height +
                       mData.mCbCrStride * mData.mCbCrSize.height;
   mBackBuffer = MakeUnique<uint8_t[]>(bufferSize);
   std::fill_n(mBackBuffer.get(), bufferSize, 42);
   mData.mYChannel = mBackBuffer.get();
   mData.mCbChannel = mData.mYChannel + mData.mYStride * mData.mYSize.height;
   mData.mCrChannel =
       mData.mCbChannel + mData.mCbCrStride * mData.mCbCrSize.height;
 }
コード例 #15
0
nsresult
BluetoothDaemonSocketModule::ConnectCmd(const BluetoothAddress& aBdAddr,
                                        BluetoothSocketType aType,
                                        const BluetoothUuid& aServiceUuid,
                                        int aChannel, bool aEncrypt,
                                        bool aAuth,
                                        BluetoothSocketResultHandler* aRes)
{
  MOZ_ASSERT(NS_IsMainThread());

  UniquePtr<DaemonSocketPDU> pdu =
    MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_CONNECT,
                                0);

  nsresult rv = PackPDU(
    aBdAddr,
    aType,
    aServiceUuid,
    PackConversion<int, int32_t>(aChannel),
    SocketFlags(aEncrypt, aAuth), *pdu);
  if (NS_FAILED(rv)) {
    return rv;
  }
  rv = Send(pdu.get(), aRes);
  if (NS_FAILED(rv)) {
    return rv;
  }
  Unused << pdu.release();
  return rv;
}
コード例 #16
0
ファイル: WinNSPR.cpp プロジェクト: stspyder/mozjs
PRThread*
PR_CreateThread(PRThreadType type,
                void (*start)(void* arg),
                void* arg,
                PRThreadPriority priority,
                PRThreadScope scope,
                PRThreadState state,
                uint32_t stackSize)
{
    MOZ_ASSERT(type == PR_USER_THREAD);
    MOZ_ASSERT(priority == PR_PRIORITY_NORMAL);

    // We assume that the first call to PR_CreateThread happens on the main
    // thread.
    if (!gInitialized)
        Initialize();

    UniquePtr<nspr::Thread> t;
    t.reset(js_new<nspr::Thread>(start, arg, state != PR_UNJOINABLE_THREAD));
    if (!t)
        return nullptr;

    t->thread = CreateThread(NULL, stackSize, &nspr::Thread::ThreadRoutine,
                             t.get(), STACK_SIZE_PARAM_IS_A_RESERVATION, &t->threadId);
    if (!t->thread)
        return nullptr;

    return t.release();
}
コード例 #17
0
ファイル: TestCaching.cpp プロジェクト: luke-chang/gecko-1
void
TestCache(const Completion aCompletion,
          bool aExpectedHas,
          bool aExpectedConfirmed,
          bool aExpectedInCache,
          T* aCache = nullptr)
{
  bool has, inCache, confirmed;
  uint32_t matchLength;

  if (aCache) {
    aCache->Has(aCompletion, &has, &matchLength, &confirmed);
    inCache = aCache->IsInCache(aCompletion.ToUint32());
  } else {
    _PrefixArray array = { GeneratePrefix(_Fragment("cache.notexpired.com/"), 10),
                           GeneratePrefix(_Fragment("cache.expired.com/"), 8),
                           GeneratePrefix(_Fragment("gound.com/"), 5),
                           GeneratePrefix(_Fragment("small.com/"), 4)
                         };

    UniquePtr<T> cache = SetupLookupCache<T>(array);

    // Create an expired entry and a non-expired entry
    SetupCacheEntry(cache.get(), _Fragment("cache.notexpired.com/"));
    SetupCacheEntry(cache.get(), _Fragment("cache.expired.com/"), true, true);

    cache->Has(aCompletion, &has, &matchLength, &confirmed);
    inCache = cache->IsInCache(aCompletion.ToUint32());
  }

  EXPECT_EQ(has, aExpectedHas);
  EXPECT_EQ(confirmed, aExpectedConfirmed);
  EXPECT_EQ(inCache, aExpectedInCache);
}
コード例 #18
0
ファイル: NativeCollation.cpp プロジェクト: webos21/xi
//static jbyteArray NativeCollation_getSortKey(JNIEnv* env, jclass, jint address, jstring source0) {
JNIEXPORT jbyteArray JNICALL
Java_com_ibm_icu4jni_text_NativeCollation_getSortKey(JNIEnv* env, jclass,
		jint address, jstring source0) {
	ScopedJavaUnicodeString source(env, source0);
	const UCollator* collator = toCollator(address);
	uint8_t byteArray[UCOL_MAX_BUFFER * 2];
	UniquePtr<uint8_t[]> largerByteArray;
	uint8_t* usedByteArray = byteArray;
	const UChar* chars = source.unicodeString().getBuffer();
	size_t charCount = source.unicodeString().length();
	size_t byteArraySize = ucol_getSortKey(collator, chars, charCount,
			usedByteArray, sizeof(byteArray) - 1);
	if (byteArraySize > sizeof(byteArray) - 1) {
		// didn't fit, try again with a larger buffer.
		largerByteArray.reset(new uint8_t[byteArraySize + 1]);
		usedByteArray = largerByteArray.get();
		byteArraySize = ucol_getSortKey(collator, chars, charCount,
				usedByteArray, byteArraySize);
	}
	if (byteArraySize == 0) {
		return NULL;
	}
	jbyteArray result = env->NewByteArray(byteArraySize);
	env->SetByteArrayRegion(result, 0, byteArraySize,
			reinterpret_cast<jbyte*> (usedByteArray));
	return result;
}
コード例 #19
0
ファイル: postscript_io.C プロジェクト: friedmud/libmesh
void PostscriptIO::plot_quadratic_elem(const Elem * elem)
{
  for (unsigned int ns=0; ns<elem->n_sides(); ++ns)
    {
      // Build the quadratic side
      UniquePtr<const Elem> side = elem->build_side_ptr(ns);

      // Be sure it's quadratic (Edge2).  Eventually we could
      // handle cubic elements as well...
      libmesh_assert_equal_to ( side->type(), EDGE3 );

      _out << "0 sg ";

      // Move to the first point on this side.
      _current_point = (side->point(0) - _offset) * _scale;
      _out << _current_point(0) << " " << _current_point(1) << " "; // write x y
      _out << "m ";

      // Compute _bezier_coeffs for this edge.  This fills up
      // the _bezier_coeffs vector.
      this->_compute_edge_bezier_coeffs(side.get());

      // Print curveto path to file
      for (unsigned int i=0; i<_bezier_coeffs.size(); ++i)
        _out << _bezier_coeffs[i](0) << " " << _bezier_coeffs[i](1) << " ";
      _out << " cs\n";
    }
}
コード例 #20
0
ファイル: Compatibility.cpp プロジェクト: djg/gecko-dev
bool Compatibility::IsModuleVersionLessThan(HMODULE aModuleHandle,
                                            unsigned long long aVersion) {
  // Get the full path to the dll.
  // We start with MAX_PATH, but the path can actually be longer.
  DWORD fnSize = MAX_PATH;
  UniquePtr<wchar_t[]> fileName;
  while (true) {
    fileName = MakeUnique<wchar_t[]>(fnSize);
    DWORD retLen = ::GetModuleFileNameW(aModuleHandle, fileName.get(), fnSize);
    MOZ_ASSERT(retLen != 0);
    if (retLen == 0) {
      return true;
    }
    if (retLen == fnSize && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
      // The buffer was too short. Increase the size and try again.
      fnSize *= 2;
    }
    break;  // Success!
  }

  // Get the version info from the file.
  DWORD length = ::GetFileVersionInfoSizeW(fileName.get(), nullptr);
  if (length == 0) {
    return true;
  }

  auto versionInfo = MakeUnique<unsigned char[]>(length);
  if (!::GetFileVersionInfoW(fileName.get(), 0, length, versionInfo.get())) {
    return true;
  }

  UINT uLen;
  VS_FIXEDFILEINFO* fixedFileInfo = nullptr;
  if (!::VerQueryValueW(versionInfo.get(), L"\\", (LPVOID*)&fixedFileInfo,
                        &uLen)) {
    return true;
  }

  // Combine into a 64 bit value for comparison.
  unsigned long long version =
      ((unsigned long long)fixedFileInfo->dwFileVersionMS) << 32 |
      ((unsigned long long)fixedFileInfo->dwFileVersionLS);

  return version < aVersion;
}
コード例 #21
0
ファイル: gfxBlur.cpp プロジェクト: Andrel322/gecko-dev
gfxContext*
gfxAlphaBoxBlur::Init(const gfxRect& aRect,
                      const gfxIntSize& aSpreadRadius,
                      const gfxIntSize& aBlurRadius,
                      const gfxRect* aDirtyRect,
                      const gfxRect* aSkipRect)
{
    mozilla::gfx::Rect rect(Float(aRect.x), Float(aRect.y),
                            Float(aRect.width), Float(aRect.height));
    IntSize spreadRadius(aSpreadRadius.width, aSpreadRadius.height);
    IntSize blurRadius(aBlurRadius.width, aBlurRadius.height);
    UniquePtr<Rect> dirtyRect;
    if (aDirtyRect) {
      dirtyRect = MakeUnique<Rect>(Float(aDirtyRect->x),
                                   Float(aDirtyRect->y),
                                   Float(aDirtyRect->width),
                                   Float(aDirtyRect->height));
    }
    UniquePtr<Rect> skipRect;
    if (aSkipRect) {
      skipRect = MakeUnique<Rect>(Float(aSkipRect->x),
                                  Float(aSkipRect->y),
                                  Float(aSkipRect->width),
                                  Float(aSkipRect->height));
    }

    mBlur = MakeUnique<AlphaBoxBlur>(rect, spreadRadius, blurRadius, dirtyRect.get(), skipRect.get());
    size_t blurDataSize = mBlur->GetSurfaceAllocationSize();
    if (blurDataSize == 0)
        return nullptr;

    IntSize size = mBlur->GetSize();

    // Make an alpha-only surface to draw on. We will play with the data after
    // everything is drawn to create a blur effect.
    mData = new (std::nothrow) unsigned char[blurDataSize];
    if (!mData) {
        return nullptr;
    }
    memset(mData, 0, blurDataSize);

    mozilla::RefPtr<DrawTarget> dt =
        gfxPlatform::GetPlatform()->CreateDrawTargetForData(mData, size,
                                                            mBlur->GetStride(),
                                                            SurfaceFormat::A8);
    if (!dt) {
        return nullptr;
    }

    IntRect irect = mBlur->GetRect();
    gfxPoint topleft(irect.TopLeft().x, irect.TopLeft().y);

    mContext = new gfxContext(dt);
    mContext->SetMatrix(gfxMatrix::Translation(-topleft));

    return mContext;
}
コード例 #22
0
static jstring NativeDecimalFormat_getTextAttribute(JNIEnv* env, jclass, jlong addr, jint javaAttr) {
    UErrorCode status = U_ZERO_ERROR;
    UNumberFormat* fmt = toUNumberFormat(addr);
    UNumberFormatTextAttribute attr = static_cast<UNumberFormatTextAttribute>(javaAttr);

    // Find out how long the result will be...
    UniquePtr<UChar[]> chars;
    uint32_t charCount = 0;
    uint32_t desiredCount = unum_getTextAttribute(fmt, attr, chars.get(), charCount, &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        // ...then get it.
        status = U_ZERO_ERROR;
        charCount = desiredCount + 1;
        chars.reset(new UChar[charCount]);
        charCount = unum_getTextAttribute(fmt, attr, chars.get(), charCount, &status);
    }
    return maybeThrowIcuException(env, "unum_getTextAttribute", status) ? NULL : env->NewString(chars.get(), charCount);
}
コード例 #23
0
// static
nsLanguageAtomService*
nsLanguageAtomService::GetService()
{
  static UniquePtr<nsLanguageAtomService> gLangAtomService;
  if (!gLangAtomService) {
    gLangAtomService = MakeUnique<nsLanguageAtomService>();
    ClearOnShutdown(&gLangAtomService);
  }
  return gLangAtomService.get();
}
コード例 #24
0
ファイル: GeckoSampler.cpp プロジェクト: valenting/gecko-dev
JSObject* GeckoSampler::ToJSObject(JSContext *aCx, double aSinceTime)
{
  JS::RootedValue val(aCx);
  {
    UniquePtr<char[]> buf = ToJSON(aSinceTime);
    NS_ConvertUTF8toUTF16 js_string(nsDependentCString(buf.get()));
    MOZ_ALWAYS_TRUE(JS_ParseJSON(aCx, static_cast<const char16_t*>(js_string.get()),
                                 js_string.Length(), &val));
  }
  return &val.toObject();
}
コード例 #25
0
ファイル: RilSocket.cpp プロジェクト: TheGuy82/gecko-dev
nsresult
RilSocketIO::QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer)
{
  MOZ_ASSERT(aBuffer);

  if (!mBuffer) {
    mBuffer = MakeUnique<UnixSocketRawData>(MAX_READ_SIZE);
  }
  *aBuffer = mBuffer.get();

  return NS_OK;
}
コード例 #26
0
void EpetraVector<T>::add_vector (const NumericVector<T> & V_in,
                                  const SparseMatrix<T> & A_in)
{
  const EpetraVector<T> * V = cast_ptr<const EpetraVector<T> *>(&V_in);
  const EpetraMatrix<T> * A = cast_ptr<const EpetraMatrix<T> *>(&A_in);

  // FIXME - does Trilinos let us do this *without* memory allocation?
  UniquePtr<NumericVector<T> > temp = V->zero_clone();
  EpetraVector<T> * tempV = cast_ptr<EpetraVector<T> *>(temp.get());
  A->mat()->Multiply(false, *V->_vec, *tempV->_vec);
  *this += *temp;
}
コード例 #27
0
ファイル: CookerRegistry.cpp プロジェクト: lachlanorr/gaen
void CookerRegistry::register_cooker(UniquePtr<Cooker> pCooker)
{
    for (const ChefString & rawExt : pCooker->rawExts())
    {
        PANIC_IF(sRawExtToCooker.find(rawExt) != sRawExtToCooker.end(),
                 "Multiple cookers registered for same raw extension: %s",
                 rawExt);

        sRawExtToCooker[rawExt] = pCooker.get();
    }

    for (const ChefString & cookedExt : pCooker->cookedExtsExclusive())
    {
        PANIC_IF(sCookedExtToCooker.find(cookedExt) != sCookedExtToCooker.end(),
                 "Multiple cookers registered for same cooked extension: %s",
                 cookedExt);

        sCookedExtToCooker[cookedExt] = pCooker.get();
    }

    sCookers.emplace_back(std::move(pCooker));
}
コード例 #28
0
void
ProfileGatherer::Finish()
{
  MOZ_ASSERT(NS_IsMainThread());

  if (!mTicker) {
    // We somehow got called after we were cancelled! This shouldn't
    // be possible, but doing a belt-and-suspenders check to be sure.
    return;
  }

  UniquePtr<char[]> buf = mTicker->ToJSON(mSinceTime);

  nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
  if (os) {
    DebugOnly<nsresult> rv = os->RemoveObserver(this, "profiler-subprocess");
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "RemoveObserver failed");
  }

  AutoJSAPI jsapi;
  if (NS_WARN_IF(!jsapi.Init(mPromise->GlobalJSObject()))) {
    // We're really hosed if we can't get a JS context for some reason.
    Reset();
    return;
  }

  JSContext* cx = jsapi.cx();

  // Now parse the JSON so that we resolve with a JS Object.
  JS::RootedValue val(cx);
  {
    NS_ConvertUTF8toUTF16 js_string(nsDependentCString(buf.get()));
    if (!JS_ParseJSON(cx, static_cast<const char16_t*>(js_string.get()),
                      js_string.Length(), &val)) {
      if (!jsapi.HasException()) {
        mPromise->MaybeReject(NS_ERROR_DOM_UNKNOWN_ERR);
      } else {
        JS::RootedValue exn(cx);
        DebugOnly<bool> gotException = jsapi.StealException(&exn);
        MOZ_ASSERT(gotException);

        jsapi.ClearException();
        mPromise->MaybeReject(cx, exn);
      }
    } else {
      mPromise->MaybeResolve(val);
    }
  }

  Reset();
}
コード例 #29
0
ファイル: Sandbox.cpp プロジェクト: carriercomm/system-addons
// Common code for sandbox startup.
static void
SetCurrentProcessSandbox(UniquePtr<sandbox::bpf_dsl::Policy> aPolicy)
{
    MOZ_ASSERT(gSandboxCrashFunc);

    // Note: PolicyCompiler borrows the policy and registry for its
    // lifetime, but does not take ownership of them.
    sandbox::bpf_dsl::PolicyCompiler compiler(aPolicy.get(),
            sandbox::Trap::Registry());
    auto program = compiler.Compile();
    if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
        sandbox::bpf_dsl::DumpBPF::PrintProgram(*program);
    }

    InstallSigSysHandler();

#ifdef MOZ_ASAN
    __sanitizer_sandbox_arguments asanArgs;
    asanArgs.coverage_sandboxed = 1;
    asanArgs.coverage_fd = -1;
    asanArgs.coverage_max_block_size = 0;
    __sanitizer_sandbox_on_notify(&asanArgs);
#endif

    // The syscall takes a C-style array, so copy the vector into one.
    size_t programLen = program->size();
    UniquePtr<sock_filter[]> flatProgram(new sock_filter[programLen]);
    for (auto i = program->begin(); i != program->end(); ++i) {
        flatProgram[i - program->begin()] = *i;
    }

    sock_fprog fprog;
    fprog.filter = flatProgram.get();
    fprog.len = static_cast<unsigned short>(programLen);
    MOZ_RELEASE_ASSERT(static_cast<size_t>(fprog.len) == programLen);

    const SandboxInfo info = SandboxInfo::Get();
    if (info.Test(SandboxInfo::kHasSeccompTSync)) {
        if (info.Test(SandboxInfo::kVerbose)) {
            SANDBOX_LOG_ERROR("using seccomp tsync");
        }
        ApplySandboxWithTSync(&fprog);
    } else {
        if (info.Test(SandboxInfo::kVerbose)) {
            SANDBOX_LOG_ERROR("no tsync support; using signal broadcast");
        }
        BroadcastSetThreadSandbox(&fprog);
    }
    MOZ_RELEASE_ASSERT(!gChrootHelper, "forgot to chroot");
}
コード例 #30
0
ファイル: JsepTrack.cpp プロジェクト: cstipkovic/gecko-dev
void
JsepTrack::Negotiate(const SdpMediaSection& answer,
                     const SdpMediaSection& remote)
{
  PtrVector<JsepCodecDescription> negotiatedCodecs;
  negotiatedCodecs.values = GetCodecClones();

  std::map<std::string, std::string> formatChanges;
  NegotiateCodecs(remote,
                  &negotiatedCodecs.values,
                  &formatChanges);

  // Use |formatChanges| to update mPrototypeCodecs
  size_t insertPos = 0;
  for (size_t i = 0; i < mPrototypeCodecs.values.size(); ++i) {
    if (formatChanges.count(mPrototypeCodecs.values[i]->mDefaultPt)) {
      // Update the payload type to what was negotiated
      mPrototypeCodecs.values[i]->mDefaultPt =
        formatChanges[mPrototypeCodecs.values[i]->mDefaultPt];
      // Move this negotiated codec up front
      std::swap(mPrototypeCodecs.values[insertPos],
                mPrototypeCodecs.values[i]);
      ++insertPos;
    }
  }

  EnsureNoDuplicatePayloadTypes(&mPrototypeCodecs.values);

  UniquePtr<JsepTrackNegotiatedDetails> negotiatedDetails =
      MakeUnique<JsepTrackNegotiatedDetails>();

  CreateEncodings(remote, negotiatedCodecs.values, negotiatedDetails.get());

  if (answer.GetAttributeList().HasAttribute(SdpAttribute::kExtmapAttribute)) {
    for (auto& extmapAttr : answer.GetAttributeList().GetExtmap().mExtmaps) {
      negotiatedDetails->mExtmap[extmapAttr.extensionname] = extmapAttr;
    }
  }

  if (mDirection == sdp::kRecv) {
    mSsrcs.clear();
    if (remote.GetAttributeList().HasAttribute(SdpAttribute::kSsrcAttribute)) {
      for (auto& ssrcAttr : remote.GetAttributeList().GetSsrc().mSsrcs) {
        AddSsrc(ssrcAttr.ssrc);
      }
    }
  }

  mNegotiatedDetails = Move(negotiatedDetails);
}