1// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4
5#include "bin/crypto.h"
6#include "bin/dartutils.h"
7
8#include "include/dart_api.h"
9
10namespace dart {
11namespace bin {
12
13void FUNCTION_NAME(Crypto_GetRandomBytes)(Dart_NativeArguments args) {
14 Dart_Handle count_obj = Dart_GetNativeArgument(args, 0);
15 const int64_t kMaxRandomBytes = 4096;
16 int64_t count64 = 0;
17 if (!DartUtils::GetInt64Value(count_obj, &count64) || (count64 < 0) ||
18 (count64 > kMaxRandomBytes)) {
19 Dart_Handle error = DartUtils::NewString(
20 "Invalid argument: count must be a positive int "
21 "less than or equal to 4096.");
22 Dart_ThrowException(error);
23 }
24 intptr_t count = static_cast<intptr_t>(count64);
25 uint8_t* buffer = Dart_ScopeAllocate(count);
26 ASSERT(buffer != NULL);
27 if (!Crypto::GetRandomBytes(count, buffer)) {
28 Dart_ThrowException(DartUtils::NewDartOSError());
29 UNREACHABLE();
30 }
31 Dart_Handle result = Dart_NewTypedData(Dart_TypedData_kUint8, count);
32 if (Dart_IsError(result)) {
33 Dart_Handle error = DartUtils::NewString("Failed to allocate storage.");
34 Dart_ThrowException(error);
35 UNREACHABLE();
36 }
37 Dart_ListSetAsBytes(result, 0, buffer, count);
38 Dart_SetReturnValue(args, result);
39}
40
41} // namespace bin
42} // namespace dart
43