2012-10-22 13:08:42 +00:00
|
|
|
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
|
|
|
|
// for details. All rights reserved. Use of this source code is governed by a
|
|
|
|
// BSD-style license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
#include "bin/crypto.h"
|
|
|
|
#include "bin/dartutils.h"
|
|
|
|
|
|
|
|
#include "include/dart_api.h"
|
|
|
|
|
2013-04-25 14:22:30 +00:00
|
|
|
namespace dart {
|
|
|
|
namespace bin {
|
|
|
|
|
2012-10-22 13:08:42 +00:00
|
|
|
void FUNCTION_NAME(Crypto_GetRandomBytes)(Dart_NativeArguments args) {
|
|
|
|
Dart_Handle count_obj = Dart_GetNativeArgument(args, 0);
|
2014-01-16 05:05:35 +00:00
|
|
|
const int64_t kMaxRandomBytes = 4096;
|
|
|
|
int64_t count64 = 0;
|
2016-11-04 19:30:56 +00:00
|
|
|
if (!DartUtils::GetInt64Value(count_obj, &count64) || (count64 < 0) ||
|
|
|
|
(count64 > kMaxRandomBytes)) {
|
|
|
|
Dart_Handle error = DartUtils::NewString(
|
|
|
|
"Invalid argument: count must be a positive int "
|
|
|
|
"less than or equal to 4096.");
|
2012-10-22 13:08:42 +00:00
|
|
|
Dart_ThrowException(error);
|
|
|
|
}
|
2014-01-16 05:05:35 +00:00
|
|
|
intptr_t count = static_cast<intptr_t>(count64);
|
2016-03-14 18:08:52 +00:00
|
|
|
uint8_t* buffer = Dart_ScopeAllocate(count);
|
2023-04-12 01:11:05 +00:00
|
|
|
ASSERT(buffer != nullptr);
|
2012-10-22 13:08:42 +00:00
|
|
|
if (!Crypto::GetRandomBytes(count, buffer)) {
|
|
|
|
Dart_ThrowException(DartUtils::NewDartOSError());
|
2014-01-16 05:05:35 +00:00
|
|
|
UNREACHABLE();
|
2012-10-22 13:08:42 +00:00
|
|
|
}
|
2013-05-31 16:36:27 +00:00
|
|
|
Dart_Handle result = Dart_NewTypedData(Dart_TypedData_kUint8, count);
|
2012-10-22 13:08:42 +00:00
|
|
|
if (Dart_IsError(result)) {
|
2012-10-31 17:56:46 +00:00
|
|
|
Dart_Handle error = DartUtils::NewString("Failed to allocate storage.");
|
2012-10-22 13:08:42 +00:00
|
|
|
Dart_ThrowException(error);
|
2014-01-16 05:05:35 +00:00
|
|
|
UNREACHABLE();
|
2012-10-22 13:08:42 +00:00
|
|
|
}
|
|
|
|
Dart_ListSetAsBytes(result, 0, buffer, count);
|
|
|
|
Dart_SetReturnValue(args, result);
|
|
|
|
}
|
2013-04-25 14:22:30 +00:00
|
|
|
|
|
|
|
} // namespace bin
|
|
|
|
} // namespace dart
|