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 <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8
9#include "include/dart_api.h"
10
11#include "bin/builtin.h"
12#include "bin/io_natives.h"
13
14namespace dart {
15namespace bin {
16
17// Lists the native function implementing basic logging facility.
18#define BUILTIN_NATIVE_LIST(V) V(Builtin_PrintString, 1)
19
20BUILTIN_NATIVE_LIST(DECLARE_FUNCTION);
21
22static struct NativeEntries {
23 const char* name_;
24 Dart_NativeFunction function_;
25 int argument_count_;
26} BuiltinEntries[] = {BUILTIN_NATIVE_LIST(REGISTER_FUNCTION)};
27
28Dart_NativeFunction Builtin::NativeLookup(Dart_Handle name,
29 int argument_count,
30 bool* auto_setup_scope) {
31 const char* function_name = NULL;
32 Dart_Handle result = Dart_StringToCString(name, &function_name);
33 if (Dart_IsError(result)) {
34 Dart_PropagateError(result);
35 }
36 ASSERT(function_name != NULL);
37 ASSERT(auto_setup_scope != NULL);
38 *auto_setup_scope = true;
39 int num_entries = sizeof(BuiltinEntries) / sizeof(struct NativeEntries);
40 for (int i = 0; i < num_entries; i++) {
41 struct NativeEntries* entry = &(BuiltinEntries[i]);
42 if ((strcmp(function_name, entry->name_) == 0) &&
43 (entry->argument_count_ == argument_count)) {
44 return reinterpret_cast<Dart_NativeFunction>(entry->function_);
45 }
46 }
47 return IONativeLookup(name, argument_count, auto_setup_scope);
48}
49
50const uint8_t* Builtin::NativeSymbol(Dart_NativeFunction nf) {
51 int num_entries = sizeof(BuiltinEntries) / sizeof(struct NativeEntries);
52 for (int i = 0; i < num_entries; i++) {
53 struct NativeEntries* entry = &(BuiltinEntries[i]);
54 if (reinterpret_cast<Dart_NativeFunction>(entry->function_) == nf) {
55 return reinterpret_cast<const uint8_t*>(entry->name_);
56 }
57 }
58 return IONativeSymbol(nf);
59}
60
61// Implementation of native functions which are used for some
62// test/debug functionality in standalone dart mode.
63void FUNCTION_NAME(Builtin_PrintString)(Dart_NativeArguments args) {
64 Dart_EnterScope();
65 intptr_t length = 0;
66 uint8_t* chars = NULL;
67 Dart_Handle str = Dart_GetNativeArgument(args, 0);
68 Dart_Handle result = Dart_StringToUTF8(str, &chars, &length);
69 if (Dart_IsError(result)) {
70 // TODO(turnidge): Consider propagating some errors here. What if
71 // an isolate gets interrupted by the embedder in the middle of
72 // Dart_StringToUTF8? We need to make sure not to swallow the
73 // interrupt.
74 fputs(Dart_GetError(result), stdout);
75 } else {
76 fwrite(chars, sizeof(*chars), length, stdout);
77 }
78 fputc('\n', stdout);
79 fflush(stdout);
80 Dart_ExitScope();
81}
82
83} // namespace bin
84} // namespace dart
85