Example #1
0
/*
 * Init available js functions
 */
static void
init_jerry ()
{
  jerry_init (JERRY_INIT_EMPTY);

  /* Create an empty JS object */
  jerry_value_t object = jerry_create_object ();

  jerry_value_t func_obj;
  jerry_value_t prop_name;

  func_obj = jerry_create_external_function (set_led);
  prop_name = jerry_create_string ((const jerry_char_t *) "setLed");
  jerry_set_property (object, prop_name, func_obj);
  jerry_release_value (prop_name);
  jerry_release_value (func_obj);

  func_obj = jerry_create_external_function (js_delay);
  prop_name = jerry_create_string ((const jerry_char_t *) "delay");
  jerry_set_property (object, prop_name, func_obj);
  jerry_release_value (prop_name);
  jerry_release_value (func_obj);

  /* Wrap the JS object (not empty anymore) into a jerry api value */
  jerry_value_t global_object = jerry_get_global_object ();

  /* Add the JS object to the global context */
  prop_name = jerry_create_string ((const jerry_char_t *) "test");
  jerry_set_property (global_object, prop_name, object);
  jerry_release_value (prop_name);
  jerry_release_value (object);
  jerry_release_value (global_object);
} /* init_jerry */
int
main (int argc, char **argv)
{
  (void) argc;
  (void) argv;
  jerry_char_t buffer[256];
  jerry_size_t bytes_copied;
  const jerryx_module_resolver_t *resolver = &jerryx_module_native_resolver;
  jerry_value_t module_name;

  jerry_init (JERRY_INIT_EMPTY);

  /* Attempt to load a non-existing module. */
  module_name = jerry_create_string ((jerry_char_t *) "some-unknown-module-name");
  jerry_value_t module = jerryx_module_resolve (module_name, &resolver, 1);
  jerry_release_value (module_name);

  TEST_ASSERT (jerry_value_has_error_flag (module));

  /* Retrieve the error message. */
  jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "message");
  jerry_value_t prop = jerry_get_property (module, prop_name);

  /* Assert that the error message is a string with specific contents. */
  TEST_ASSERT (jerry_value_is_string (prop));

  bytes_copied = jerry_substring_to_utf8_char_buffer (prop, 0, 254, buffer, 256);
  buffer[bytes_copied] = 0;
  TEST_ASSERT (!strcmp ((const char *) buffer, "Module not found"));

  /* Release the error message property name and value. */
  jerry_release_value (prop);
  jerry_release_value (prop_name);

  /* Retrieve the moduleName property. */
  prop_name = jerry_create_string ((const jerry_char_t *) "moduleName");
  prop = jerry_get_property (module, prop_name);

  /* Assert that the moduleName property is a string containing the requested module name. */
  TEST_ASSERT (jerry_value_is_string (prop));

  bytes_copied = jerry_substring_to_utf8_char_buffer (prop, 0, 254, buffer, 256);
  buffer[bytes_copied] = 0;
  TEST_ASSERT (!strcmp ((const char *) buffer, "some-unknown-module-name"));

  /* Release everything. */
  jerry_release_value (prop);
  jerry_release_value (prop_name);
  jerry_release_value (module);

  return 0;
} /* main */
Example #3
0
void iotjs_tizen_app_control_cb(app_control_h app_control, void* user_data) {
  DDDLOG("%s", __func__);

  iotjs_environment_t* env = iotjs_environment_get();

  if (env->state != kRunningMain && env->state != kRunningLoop) {
    return;
  }

  const char* event_emitter_name = IOTJS_MAGIC_STRING_TIZEN;
  const char* event_name = IOTJS_MAGIC_STRING_APP_CONTROL;

  jerry_value_t tizen = iotjs_module_get(event_emitter_name);
  jerry_value_t fn = iotjs_jval_get_property(tizen, IOTJS_MAGIC_STRING_EMIT);

  if (jerry_value_is_function(fn) == false) {
    DDDLOG("tizen module is not loaded");
    goto exit;
  }

  // parse app control
  char* json = NULL;
  bundle* b = NULL;

  app_control_export_as_bundle(app_control, &b);

  if (BUNDLE_ERROR_NONE != bundle_to_json(b, &json)) {
    DDLOG("bundle_to_json failed");
    bundle_free(b);
    return;
  }
  DDDLOG("JSON: %s", json);

  // call emit
  jerry_value_t jargv[2] = { jerry_create_string(
                                 (const jerry_char_t*)event_name),
                             jerry_create_string((const jerry_char_t*)json) };

  iotjs_invoke_callback(fn, tizen, jargv, 2);
  jerry_release_value(jargv[0]);
  jerry_release_value(jargv[1]);

  free(json);
  bundle_free(b);

exit:
  jerry_release_value(fn);
}
Example #4
0
static bool bridge_native_call(const char* module_name, const char* func_name,
                               const char* message,
                               iotjs_string_t* output_str) {
  bool result = false;

  jerry_value_t jmodule = iotjs_module_get(module_name);
  jerry_value_t jfunc = iotjs_jval_get_property(jmodule, func_name);

  if (jerry_value_is_function(jfunc) == false) {
    return result;
  }

  jerry_value_t jval = jerry_create_string((const jerry_char_t*)message);
  jerry_value_t jres =
      iotjs_invoke_callback_with_result(jfunc, jmodule, &jval, 1);

  if (jerry_value_is_string(jres)) {
    IOTJS_ASSERT(output_str != NULL);
    *output_str = iotjs_jval_as_string(jres);
    result = true;
  }

  jerry_release_value(jfunc);
  jerry_release_value(jres);
  jerry_release_value(jval);
  return result;
}
Example #5
0
static jerry_value_t
handler (const jerry_value_t func_obj_val, /**< function object */
         const jerry_value_t this_val, /**< this value */
         const jerry_value_t args_p[], /**< arguments list */
         const jerry_length_t args_cnt) /**< arguments length */
{
  char buffer[32];
  jerry_size_t sz;

  printf ("ok %d %d %p %d\n", func_obj_val, this_val, args_p, args_cnt);

  JERRY_ASSERT (args_cnt == 2);

  JERRY_ASSERT (jerry_value_is_string (args_p[0]));
  sz = jerry_get_string_size (args_p[0]);
  JERRY_ASSERT (sz == 1);
  sz = jerry_string_to_char_buffer (args_p[0],
                                    (jerry_char_t *) buffer,
                                    sz);
  JERRY_ASSERT (sz == 1);
  JERRY_ASSERT (!strncmp (buffer, "1", (size_t) sz));

  JERRY_ASSERT (jerry_value_is_boolean (args_p[1]));

  return jerry_create_string ((jerry_char_t *) "string from handler");
} /* handler */
Example #6
0
static jerry_value_t
handler_construct (const jerry_value_t func_obj_val, /**< function object */
                   const jerry_value_t this_val, /**< this value */
                   const jerry_value_t args_p[], /**< arguments list */
                   const jerry_length_t args_cnt) /**< arguments length */
{
  printf ("ok construct %d %d %p %d\n", func_obj_val, this_val, args_p, args_cnt);

  JERRY_ASSERT (jerry_value_is_object (this_val));

  JERRY_ASSERT (args_cnt == 1);
  JERRY_ASSERT (jerry_value_is_boolean (args_p[0]));
  JERRY_ASSERT (jerry_get_boolean_value (args_p[0]) == true);

  jerry_value_t field_name = jerry_create_string ((jerry_char_t *) "value_field");
  jerry_set_property (this_val, field_name, args_p[0]);
  jerry_release_value (field_name);

  jerry_set_object_native_handle (this_val,
                                  (uintptr_t) 0x0000000000000000ull,
                                  handler_construct_freecb);

  uintptr_t ptr;
  bool is_ok = jerry_get_object_native_handle (this_val, &ptr);
  JERRY_ASSERT (is_ok && ptr == (uintptr_t) 0x0000000000000000ull);

  /* check if setting handle for second time is handled correctly */
  jerry_set_object_native_handle (this_val,
                                  (uintptr_t) 0x0012345678abcdefull,
                                  handler_construct_freecb);

  return jerry_create_boolean (true);
} /* handler_construct */
Example #7
0
iotjs_jval_t iotjs_jval_create_string_raw(const char* data) {
  iotjs_jval_t jval;
  IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);

  _this->value = jerry_create_string((const jerry_char_t*)data);

  return jval;
}
Example #8
0
static jerry_value_t
get_property (const jerry_value_t obj_val, /**< object value */
              const char *str_p) /**< property name */
{
  jerry_value_t prop_name_val = jerry_create_string ((const jerry_char_t *) str_p);
  jerry_value_t ret_val = jerry_get_property (obj_val, prop_name_val);
  jerry_release_value (prop_name_val);
  return ret_val;
} /* get_property */
Example #9
0
void jerry_start ()
{
  srand ((unsigned) jerry_port_get_current_time ());
  jerry_init (JERRY_INIT_EMPTY);
  jerry_value_t global_obj_val = jerry_get_global_object ();
  jerry_value_t print_func_name_val = jerry_create_string ((jerry_char_t *) "print");
  print_function = jerry_get_property (global_obj_val, print_func_name_val);
  jerry_release_value (print_func_name_val);
  jerry_release_value (global_obj_val);
}
Example #10
0
static void AfterAsync(uv_fs_t* req) {
  const jerry_value_t cb = *IOTJS_UV_REQUEST_JSCALLBACK(req);
  IOTJS_ASSERT(jerry_value_is_function(cb));

  jerry_value_t jargs[2] = { 0 };
  size_t jargc = 0;
  if (req->result < 0) {
    jerry_value_t jerror = iotjs_create_uv_exception(req->result, "open");
    jargs[jargc++] = jerror;
  } else {
    jargs[jargc++] = jerry_create_null();
    switch (req->fs_type) {
      case UV_FS_CLOSE: {
        break;
      }
      case UV_FS_OPEN:
      case UV_FS_READ:
      case UV_FS_WRITE: {
        jargs[jargc++] = jerry_create_number((double)req->result);
        break;
      }
      case UV_FS_SCANDIR: {
        int r;
        uv_dirent_t ent;
        uint32_t idx = 0;
        jargs[jargc++] = jerry_create_array(0);
        while ((r = uv_fs_scandir_next(req, &ent)) != UV_EOF) {
          jerry_value_t name =
              jerry_create_string((const jerry_char_t*)ent.name);
          iotjs_jval_set_property_by_index(jargs[1], idx, name);
          jerry_release_value(name);
          idx++;
        }
        break;
      }
      case UV_FS_FSTAT:
      case UV_FS_STAT: {
        uv_stat_t s = (req->statbuf);
        jargs[jargc++] = MakeStatObject(&s);
        break;
      }
      default: { break; }
    }
  }

  iotjs_invoke_callback(cb, jerry_create_undefined(), jargs, jargc);

  jerry_release_value(jargs[0]);
  jerry_release_value(jargs[1]);
  uv_fs_req_cleanup(req);
  iotjs_uv_request_destroy((uv_req_t*)req);
}
Example #11
0
void iotjs_jval_set_property_jval(const iotjs_jval_t* jobj, const char* name,
                                  const iotjs_jval_t* val) {
  const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
  IOTJS_ASSERT(iotjs_jval_is_object(jobj));

  jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name));
  jerry_value_t value = iotjs_jval_as_raw(val);
  jerry_value_t ret_val = jerry_set_property(_this->value, prop_name, value);
  jerry_release_value(prop_name);

  IOTJS_ASSERT(!jerry_value_has_error_flag(ret_val));
  jerry_release_value(ret_val);
}
Example #12
0
jerry_value_t init_$MODULE_NAME$(void) {
  jerry_value_t object = jerry_create_object();

  jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)"demokey");
  jerry_value_t prop_value = jerry_create_number(3.4);

  jerry_set_property(object, prop_name, prop_value);

  jerry_release_value(prop_name);
  jerry_release_value(prop_value);

  return object;
}
/**
 * Register a JavaScript value in the global object.
 */
static void
register_js_value (const char *name_p, /**< name of the function */
                   jerry_value_t value) /**< JS value */
{
  jerry_value_t global_obj_val = jerry_get_global_object ();

  jerry_value_t name_val = jerry_create_string ((const jerry_char_t *) name_p);
  jerry_value_t result_val = jerry_set_property (global_obj_val, name_val, value);
  TEST_ASSERT (jerry_value_is_boolean (result_val));

  jerry_release_value (name_val);
  jerry_release_value (global_obj_val);

  jerry_release_value (result_val);
} /* register_js_value */
Example #14
0
static jerry_value_t
callback_func (const jerry_value_t function_obj,
               const jerry_value_t this_val,
               const jerry_value_t args_p[],
               const jerry_length_t args_count)
{
  JERRY_UNUSED (function_obj);
  JERRY_UNUSED (this_val);
  JERRY_UNUSED (args_p);
  JERRY_UNUSED (args_count);

  jerry_value_t value = jerry_create_string ((jerry_char_t *) "Abort run!");
  jerry_value_set_abort_flag (&value);
  return value;
} /* callback_func */
Example #15
0
static bool
register_native_function (const char* name,
                          jerry_external_handler_t handler)
{
  jerry_value_t global_object_val = jerry_get_global_object ();
  jerry_value_t reg_function = jerry_create_external_function (handler);

  bool is_ok = true;

  if (!(jerry_value_is_function (reg_function)
        && jerry_value_is_constructor (reg_function)))
  {
    is_ok = false;
    printf ("Error: create_external_function failed !!!\r\n");
    jerry_release_value (global_object_val);
    jerry_release_value (reg_function);
    return is_ok;
  }

  if (jerry_value_has_error_flag (reg_function))
  {
    is_ok = false;
    printf ("Error: create_external_function has error flag! \n\r");
    jerry_release_value (global_object_val);
    jerry_release_value (reg_function);
    return is_ok;
  }

  jerry_value_t jerry_name = jerry_create_string ((jerry_char_t *) name);

  jerry_value_t set_result = jerry_set_property (global_object_val,
                                                 jerry_name,
                                                 reg_function);


  if (jerry_value_has_error_flag (set_result))
  {
    is_ok = false;
    printf ("Error: register_native_function failed: [%s]\r\n", name);
  }

  jerry_release_value (jerry_name);
  jerry_release_value (global_object_val);
  jerry_release_value (reg_function);
  jerry_release_value (set_result);

  return is_ok;
}
Example #16
0
static void SetProcessArgv(jerry_value_t process) {
  const iotjs_environment_t* env = iotjs_environment_get();
  uint32_t argc = iotjs_environment_argc(env);

  jerry_value_t argv = jerry_create_array(argc);

  for (uint32_t i = 0; i < argc; ++i) {
    const char* argvi = iotjs_environment_argv(env, i);
    jerry_value_t arg = jerry_create_string((const jerry_char_t*)argvi);
    iotjs_jval_set_property_by_index(argv, i, arg);
    jerry_release_value(arg);
  }
  iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_ARGV, argv);

  jerry_release_value(argv);
}
Example #17
0
iotjs_jval_t iotjs_jval_get_property(const iotjs_jval_t* jobj,
                                     const char* name) {
  const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
  IOTJS_ASSERT(iotjs_jval_is_object(jobj));

  jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name));
  jerry_value_t res = jerry_get_property(_this->value, prop_name);
  jerry_release_value(prop_name);

  if (jerry_value_has_error_flag(res)) {
    jerry_release_value(res);
    return iotjs_jval_create_copied(iotjs_jval_get_undefined());
  }

  return iotjs_jval_create_raw(res);
}
Example #18
0
static jerry_value_t AfterSync(uv_fs_t* req, int err,
                               const char* syscall_name) {
  if (err < 0) {
    jerry_value_t jvalue = iotjs_create_uv_exception(err, syscall_name);
    jerry_value_t jerror = jerry_create_error_from_value(jvalue, true);
    return jerror;
  }

  switch (req->fs_type) {
    case UV_FS_CLOSE:
      break;
    case UV_FS_OPEN:
    case UV_FS_READ:
    case UV_FS_WRITE:
      return jerry_create_number(err);
    case UV_FS_FSTAT:
    case UV_FS_STAT: {
      uv_stat_t* s = &(req->statbuf);
      return MakeStatObject(s);
    }
    case UV_FS_MKDIR:
    case UV_FS_RMDIR:
    case UV_FS_UNLINK:
    case UV_FS_RENAME:
      return jerry_create_undefined();
    case UV_FS_SCANDIR: {
      int r;
      uv_dirent_t ent;
      uint32_t idx = 0;
      jerry_value_t ret = jerry_create_array(0);
      while ((r = uv_fs_scandir_next(req, &ent)) != UV_EOF) {
        jerry_value_t name = jerry_create_string((const jerry_char_t*)ent.name);
        iotjs_jval_set_property_by_index(ret, idx, name);
        jerry_release_value(name);
        idx++;
      }
      return ret;
    }
    default: {
      IOTJS_ASSERT(false);
      break;
    }
  }
  return jerry_create_undefined();
}
Example #19
0
napi_status napi_has_element(napi_env env, napi_value object, uint32_t index,
                             bool* result) {
  NAPI_TRY_ENV(env);
  jerry_value_t jval_object = AS_JERRY_VALUE(object);
  NAPI_TRY_TYPE(object, jval_object);

  char idx_str[17];
  sprintf(idx_str, "%d", index);
  jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)idx_str);
  jerry_value_t has_prop_val = jerry_has_own_property(jval_object, prop_name);
  jerry_release_value(prop_name);

  if (jerry_value_is_error(has_prop_val)) {
    jerry_release_value(has_prop_val);
    NAPI_RETURN(napi_generic_failure);
  }

  bool has_prop = jerry_get_boolean_value(has_prop_val);
  return napi_assign_bool(has_prop, result);
}
Example #20
0
void main (void)
{
  printf ("Jerry Compilation " __DATE__ " " __TIME__ "\n");
  jerry_init (JERRY_INIT_EMPTY);
  jerry_value_t global_obj_val = jerry_get_global_object ();

  jerry_value_t print_func_name_val = jerry_create_string ((jerry_char_t *) "print");
  print_function = jerry_get_property (global_obj_val, print_func_name_val);
  jerry_release_value (print_func_name_val);
  jerry_release_value (global_obj_val);
  if (jerry_value_has_error_flag (print_function))
  {
    printf ("Error: could not look up print function, expression results won't be printed\n");
  }

  shell_register_app_cmd_handler (shell_cmd_handler);
  shell_init ("js> ", commands);
  /* Don't call jerry_cleanup() here, as shell_init() returns after setting
     up background task to process shell input, and that task calls
     shell_cmd_handler(), etc. as callbacks. This processing happens in
     the infinite loop, so JerryScript doesn't need to be de-initialized. */
} /* main */
Example #21
0
/**
 * Check whether an error is a SyntaxError or not
 *
 * @return true - if param is SyntaxError
 *         false - otherwise
 */
static bool
jerry_value_is_syntax_error (jerry_value_t error_value) /**< error value */
{
  assert (jerry_is_feature_enabled (JERRY_FEATURE_ERROR_MESSAGES));

  if (!jerry_value_is_object (error_value))
  {
    return false;
  }

  jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *)"name");
  jerry_value_t error_name = jerry_get_property (error_value, prop_name);
  jerry_release_value (prop_name);

  if (jerry_value_has_error_flag (error_name)
      || !jerry_value_is_string (error_name))
  {
    return false;
  }

  jerry_size_t err_str_size = jerry_get_string_size (error_name);
  jerry_char_t err_str_buf[err_str_size];

  jerry_size_t sz = jerry_string_to_char_buffer (error_name, err_str_buf, err_str_size);
  jerry_release_value (error_name);

  if (sz == 0)
  {
    return false;
  }

  if (!strcmp ((char *) err_str_buf, "SyntaxError"))
  {
    return true;
  }

  return false;
} /* jerry_value_is_syntax_error */
Example #22
0
void main (void)
{
  srand ((unsigned) jerry_port_get_current_time ());
  uint32_t zephyr_ver = sys_kernel_version_get ();
  printf ("JerryScript build: " __DATE__ " " __TIME__ "\n");
  printf ("JerryScript API %d.%d\n", JERRY_API_MAJOR_VERSION, JERRY_API_MINOR_VERSION);
  printf ("Zephyr version %d.%d.%d\n", (int)SYS_KERNEL_VER_MAJOR (zephyr_ver),
    (int)SYS_KERNEL_VER_MINOR (zephyr_ver),
    (int)SYS_KERNEL_VER_PATCHLEVEL (zephyr_ver));

  zephyr_getline_init ();
  jerry_init (JERRY_INIT_EMPTY);
  register_js_function ("print", jerryx_handler_print);
  jerry_value_t global_obj_val = jerry_get_global_object ();

  jerry_value_t print_func_name_val = jerry_create_string ((jerry_char_t *) "print");
  print_function = jerry_get_property (global_obj_val, print_func_name_val);
  jerry_release_value (print_func_name_val);
  jerry_release_value (global_obj_val);
  if (jerry_value_is_error (print_function))
  {
    printf ("Error: could not look up print function, expression results won't be printed\n");
  }

  while (1)
  {
    char *s;
    printf("js> ");
    fflush(stdout);
    s = zephyr_getline ();
    if (*s)
    {
      shell_cmd_handler (s);
    }
  }

  /* As we never retturn from REPL above, don't call jerry_cleanup() here. */
} /* main */
Example #23
0
int
main (void)
{
  TEST_INIT ();

  jerry_init (JERRY_INIT_EMPTY);

  const jerry_char_t test_eval_function[] = "function demo(a) { return a + 1; }; demo";

  test_entry_t entries[] =
  {
    ENTRY (JERRY_TYPE_NUMBER, jerry_create_number (-33.0)),
    ENTRY (JERRY_TYPE_NUMBER, jerry_create_number (3)),
    ENTRY (JERRY_TYPE_NUMBER, jerry_create_number_nan ()),
    ENTRY (JERRY_TYPE_NUMBER, jerry_create_number_infinity (false)),
    ENTRY (JERRY_TYPE_NUMBER, jerry_create_number_infinity (true)),

    ENTRY (JERRY_TYPE_BOOLEAN, jerry_create_boolean (true)),
    ENTRY (JERRY_TYPE_BOOLEAN, jerry_create_boolean (false)),

    ENTRY (JERRY_TYPE_UNDEFINED, jerry_create_undefined ()),

    ENTRY (JERRY_TYPE_OBJECT, jerry_create_object ()),
    ENTRY (JERRY_TYPE_OBJECT, jerry_create_array (10)),
    ENTRY (JERRY_TYPE_ERROR, jerry_create_error (JERRY_ERROR_TYPE, (const jerry_char_t *) "error")),

    ENTRY (JERRY_TYPE_NULL, jerry_create_null ()),

    ENTRY (JERRY_TYPE_FUNCTION, jerry_eval (test_eval_function,
                                            sizeof (test_eval_function) - 1,
                                            JERRY_PARSE_NO_OPTS)),
    ENTRY (JERRY_TYPE_FUNCTION, jerry_create_external_function (test_ext_function)),

    ENTRY (JERRY_TYPE_STRING, jerry_create_string (test_eval_function)),
    ENTRY (JERRY_TYPE_STRING, jerry_create_string ((jerry_char_t *) "")),
  };

  for (size_t idx = 0; idx < sizeof (entries) / sizeof (entries[0]); idx++)
  {
    jerry_type_t type_info = jerry_value_get_type (entries[idx].value);

    TEST_ASSERT (type_info != JERRY_TYPE_NONE);
    TEST_ASSERT (type_info == entries[idx].type_info);

    jerry_release_value (entries[idx].value);
  }

  if (jerry_is_feature_enabled (JERRY_FEATURE_SYMBOL))
  {
    jerry_value_t symbol_desc_value = jerry_create_string ((jerry_char_t *) "foo");
    jerry_value_t symbol_value = jerry_create_symbol (symbol_desc_value);
    jerry_type_t type_info = jerry_value_get_type (symbol_value);

    TEST_ASSERT (type_info != JERRY_TYPE_NONE);
    TEST_ASSERT (type_info == JERRY_TYPE_SYMBOL);

    jerry_release_value (symbol_value);
    jerry_release_value (symbol_desc_value);
  }

  jerry_cleanup ();

  return 0;
} /* main */
int
main (void)
{
  jerry_init (JERRY_INIT_EMPTY);

  /* Render strict-equal as a function. */
  jerry_value_t parse_result = jerry_parse (NULL,
                                            0,
                                            strict_equal_source,
                                            sizeof (strict_equal_source) - 1,
                                            JERRY_PARSE_STRICT_MODE);
  TEST_ASSERT (!jerry_value_is_error (parse_result));
  jerry_value_t strict_equal = jerry_run (parse_result);
  TEST_ASSERT (!jerry_value_is_error (strict_equal));
  jerry_release_value (parse_result);

  /* Create an object and associate some native data with it. */
  jerry_value_t object = jerry_create_object ();
  jerry_set_object_native_pointer (object, &test_data, &test_info);

  /* Retrieve the object by its native pointer. */

  jerry_value_t found_object;
  TEST_ASSERT (jerry_objects_foreach_by_native_info (&test_info, find_test_object_by_data, &found_object));
  jerry_value_t args[2] = {object, found_object};

  /* Assert that the correct object was retrieved. */
  jerry_value_t undefined = jerry_create_undefined ();
  jerry_value_t strict_equal_result = jerry_call_function (strict_equal, undefined, args, 2);
  TEST_ASSERT (jerry_value_is_boolean (strict_equal_result) && jerry_get_boolean_value (strict_equal_result));
  jerry_release_value (strict_equal_result);
  jerry_release_value (found_object);
  jerry_release_value (object);

  /* Collect garbage. */
  jerry_gc (JERRY_GC_SEVERITY_LOW);

  /* Attempt to retrieve the object by its native pointer again. */
  TEST_ASSERT (!jerry_objects_foreach_by_native_info (&test_info, find_test_object_by_data, &found_object));

  /* Create an object and set a property on it. */
  object = jerry_create_object ();
  jerry_value_t property_name = jerry_create_string ((jerry_char_t *) "xyzzy");
  jerry_value_t property_value = jerry_create_number (42);
  jerry_release_value (jerry_set_property (object, property_name, property_value));
  jerry_release_value (property_value);

  /* Retrieve the object by the presence of its property, placing it at args[1]. */
  args[0] = property_name;
  TEST_ASSERT (jerry_objects_foreach (find_test_object_by_property, args));

  /* Assert that the right object was retrieved and release both the original reference to it and the retrieved one. */
  args[0] = object;
  strict_equal_result = jerry_call_function (strict_equal, undefined, args, 2);
  TEST_ASSERT (jerry_value_is_boolean (strict_equal_result) && jerry_get_boolean_value (strict_equal_result));
  jerry_release_value (strict_equal_result);
  jerry_release_value (args[0]);
  jerry_release_value (args[1]);

  /* Collect garbage. */
  jerry_gc (JERRY_GC_SEVERITY_LOW);

  /* Attempt to retrieve the object by the presence of its property again. */
  args[0] = property_name;
  TEST_ASSERT (!jerry_objects_foreach (find_test_object_by_property, args));

  jerry_release_value (property_name);
  jerry_release_value (undefined);
  jerry_release_value (strict_equal);
  jerry_cleanup ();
} /* main */
Example #25
0
int
main (void)
{
  TEST_INIT ();

  jerry_init (JERRY_INIT_EMPTY);

  jerry_value_t global = jerry_get_global_object ();
  jerry_value_t callback_name = jerry_create_string ((jerry_char_t *) "callback");
  jerry_value_t func = jerry_create_external_function (callback_func);
  jerry_value_t res = jerry_set_property (global, callback_name, func);
  TEST_ASSERT (!jerry_value_is_error (res));

  jerry_release_value (res);
  jerry_release_value (func);
  jerry_release_value (callback_name);
  jerry_release_value (global);

  const char *inf_loop_code_src_p = ("while(true) {\n"
                                     "  with ({}) {\n"
                                     "    try {\n"
                                     "      callback();\n"
                                     "    } catch (e) {\n"
                                     "    } finally {\n"
                                     "    }\n"
                                     "  }\n"
                                     "}");

  jerry_value_t parsed_code_val = jerry_parse (NULL,
                                               0,
                                               (jerry_char_t *) inf_loop_code_src_p,
                                               strlen (inf_loop_code_src_p),
                                               JERRY_PARSE_NO_OPTS);

  TEST_ASSERT (!jerry_value_is_error (parsed_code_val));
  res = jerry_run (parsed_code_val);

  TEST_ASSERT (jerry_value_is_abort (res));

  jerry_release_value (res);
  jerry_release_value (parsed_code_val);

  inf_loop_code_src_p = ("function f() {"
                         "  while(true) {\n"
                         "    with ({}) {\n"
                         "      try {\n"
                         "        callback();\n"
                         "      } catch (e) {\n"
                         "      } finally {\n"
                         "      }\n"
                         "    }\n"
                         "  }"
                         "}\n"
                         "function g() {\n"
                         "  for (a in { x:5 })\n"
                         "    f();\n"
                         "}\n"
                          "\n"
                         "with({})\n"
                         " f();\n");

  parsed_code_val = jerry_parse (NULL,
                                 0,
                                 (jerry_char_t *) inf_loop_code_src_p,
                                 strlen (inf_loop_code_src_p),
                                 JERRY_PARSE_NO_OPTS);

  TEST_ASSERT (!jerry_value_is_error (parsed_code_val));
  res = jerry_run (parsed_code_val);

  TEST_ASSERT (jerry_value_is_abort (res));

  jerry_release_value (res);
  jerry_release_value (parsed_code_val);

  /* Test flag overwrites. */
  jerry_value_t value = jerry_create_string ((jerry_char_t *) "Error description");
  TEST_ASSERT (!jerry_value_is_abort (value));
  TEST_ASSERT (!jerry_value_is_error (value));

  jerry_value_set_abort_flag (&value);
  TEST_ASSERT (jerry_value_is_abort (value));
  TEST_ASSERT (jerry_value_is_error (value));

  jerry_value_set_error_flag (&value);
  TEST_ASSERT (!jerry_value_is_abort (value));
  TEST_ASSERT (jerry_value_is_error (value));

  jerry_value_set_abort_flag (&value);
  TEST_ASSERT (jerry_value_is_abort (value));
  TEST_ASSERT (jerry_value_is_error (value));

  jerry_release_value (value);

  jerry_cleanup ();
  return 0;
} /* main */
Example #26
0
static void AfterAsync(uv_fs_t* req) {
  iotjs_fs_reqwrap_t* req_wrap = (iotjs_fs_reqwrap_t*)(req->data);
  IOTJS_ASSERT(req_wrap != NULL);
  IOTJS_ASSERT(&req_wrap->req == req);

  const jerry_value_t cb = iotjs_reqwrap_jcallback(&req_wrap->reqwrap);
  IOTJS_ASSERT(jerry_value_is_function(cb));

  iotjs_jargs_t jarg = iotjs_jargs_create(2);
  if (req->result < 0) {
    jerry_value_t jerror = iotjs_create_uv_exception(req->result, "open");
    iotjs_jargs_append_jval(&jarg, jerror);
    jerry_release_value(jerror);
  } else {
    iotjs_jargs_append_null(&jarg);
    switch (req->fs_type) {
      case UV_FS_CLOSE: {
        break;
      }
      case UV_FS_OPEN:
      case UV_FS_READ:
      case UV_FS_WRITE: {
        iotjs_jargs_append_number(&jarg, (double)req->result);
        break;
      }
      case UV_FS_SCANDIR: {
        int r;
        uv_dirent_t ent;
        uint32_t idx = 0;
        jerry_value_t ret = jerry_create_array(0);
        while ((r = uv_fs_scandir_next(req, &ent)) != UV_EOF) {
          jerry_value_t name =
              jerry_create_string((const jerry_char_t*)ent.name);
          iotjs_jval_set_property_by_index(ret, idx, name);
          jerry_release_value(name);
          idx++;
        }
        iotjs_jargs_append_jval(&jarg, ret);
        jerry_release_value(ret);
        break;
      }
      case UV_FS_FSTAT:
      case UV_FS_STAT: {
        uv_stat_t s = (req->statbuf);
        jerry_value_t ret = MakeStatObject(&s);
        iotjs_jargs_append_jval(&jarg, ret);
        jerry_release_value(ret);
        break;
      }
      default: {
        iotjs_jargs_append_null(&jarg);
        break;
      }
    }
  }

  iotjs_make_callback(cb, jerry_create_undefined(), &jarg);

  iotjs_jargs_destroy(&jarg);
  iotjs_fs_reqwrap_destroy(req_wrap);
}
Example #27
0
int
main (void)
{
  TEST_INIT ();

  bool is_ok;
  jerry_size_t sz;
  jerry_value_t val_t, val_foo, val_bar, val_A, val_A_prototype, val_a, val_a_foo, val_value_field, val_p, val_np;
  jerry_value_t val_call_external;
  jerry_value_t global_obj_val, obj_val;
  jerry_value_t external_func_val, external_construct_val;
  jerry_value_t throw_test_handler_val;
  jerry_value_t parsed_code_val, proto_val, prim_val;
  jerry_value_t res, args[2];
  char buffer[32];

  is_ok = test_run_simple ("print ('Hello, World!');");
  JERRY_ASSERT (is_ok);

  is_ok = test_run_simple ("throw 'Hello World';");
  JERRY_ASSERT (!is_ok);

  jerry_init (JERRY_INIT_EMPTY);

  parsed_code_val = jerry_parse ((jerry_char_t *) test_source, strlen (test_source), false);
  JERRY_ASSERT (!jerry_value_has_error_flag (parsed_code_val));

  res = jerry_run (parsed_code_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  jerry_release_value (res);
  jerry_release_value (parsed_code_val);

  global_obj_val = jerry_get_global_object ();

  // Test corner case for jerry_string_to_char_buffer
  args[0] = jerry_create_string ((jerry_char_t *) "");
  sz = jerry_get_string_size (args[0]);
  JERRY_ASSERT (sz == 0);
  jerry_release_value (args[0]);

  // Get global.boo (non-existing field)
  val_t = get_property (global_obj_val, "boo");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_undefined (val_t));

  // Get global.t
  val_t = get_property (global_obj_val, "t");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_number (val_t)
                && jerry_get_number_value (val_t) == 1.0);
  jerry_release_value (val_t);

  // Get global.foo
  val_foo = get_property (global_obj_val, "foo");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_foo));
  JERRY_ASSERT (jerry_value_is_object (val_foo));

  // Call foo (4, 2)
  args[0] = jerry_create_number (4);
  args[1] = jerry_create_number (2);
  res = jerry_call_function (val_foo, jerry_create_undefined (), args, 2);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_number (res)
                && jerry_get_number_value (res) == 1.0);
  jerry_release_value (res);

  // Get global.bar
  val_bar = get_property (global_obj_val, "bar");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_bar));
  JERRY_ASSERT (jerry_value_is_object (val_bar));

  // Call bar (4, 2)
  res = jerry_call_function (val_bar, jerry_create_undefined (), args, 2);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_number (res)
                && jerry_get_number_value (res) == 5.0);
  jerry_release_value (res);
  jerry_release_value (val_bar);

  // Set global.t = "abcd"
  jerry_release_value (args[0]);
  args[0] = jerry_create_string ((jerry_char_t *) "abcd");
  res = set_property (global_obj_val, "t", args[0]);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (res);

  // Call foo (4, 2)
  res = jerry_call_function (val_foo, jerry_create_undefined (), args, 2);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_string (res));
  sz = jerry_get_string_size (res);
  JERRY_ASSERT (sz == 4);
  sz = jerry_string_to_char_buffer (res, (jerry_char_t *) buffer, sz);
  JERRY_ASSERT (sz == 4);
  jerry_release_value (res);
  JERRY_ASSERT (!strncmp (buffer, "abcd", (size_t) sz));
  jerry_release_value (args[0]);
  jerry_release_value (args[1]);

  // Get global.A
  val_A = get_property (global_obj_val, "A");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_A));
  JERRY_ASSERT (jerry_value_is_object (val_A));

  // Get A.prototype
  is_ok = jerry_value_is_constructor (val_A);
  JERRY_ASSERT (is_ok);
  val_A_prototype = get_property (val_A, "prototype");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_A_prototype));
  JERRY_ASSERT (jerry_value_is_object (val_A_prototype));
  jerry_release_value (val_A);

  // Set A.prototype.foo = global.foo
  res = set_property (val_A_prototype, "foo", val_foo);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (res);
  jerry_release_value (val_A_prototype);
  jerry_release_value (val_foo);

  // Get global.a
  val_a = get_property (global_obj_val, "a");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_a));
  JERRY_ASSERT (jerry_value_is_object (val_a));

  // Get a.t
  res = get_property (val_a, "t");
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_number (res)
                && jerry_get_number_value (res) == 12.0);
  jerry_release_value (res);

  // foreach properties
  val_p = get_property (global_obj_val, "p");
  is_ok = jerry_foreach_object_property (val_p, foreach, (void *) "user_data");
  JERRY_ASSERT (is_ok);

  // break foreach at third element
  int count = 0;
  is_ok = jerry_foreach_object_property (val_p, foreach_subset, &count);
  JERRY_ASSERT (is_ok);
  JERRY_ASSERT (count == 3);
  jerry_release_value (val_p);

  // foreach with throw test
  val_np = get_property (global_obj_val, "np");
  is_ok = !jerry_foreach_object_property (val_np, foreach_exception, NULL);
  JERRY_ASSERT (is_ok);
  jerry_release_value (val_np);

  // Get a.foo
  val_a_foo = get_property (val_a, "foo");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_a_foo));
  JERRY_ASSERT (jerry_value_is_object (val_a_foo));

  // Call a.foo ()
  res = jerry_call_function (val_a_foo, val_a, NULL, 0);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_number (res)
                && jerry_get_number_value (res) == 12.0);
  jerry_release_value (res);
  jerry_release_value (val_a_foo);

  jerry_release_value (val_a);

  // Create native handler bound function object and set it to 'external' variable
  external_func_val = jerry_create_external_function (handler);
  JERRY_ASSERT (jerry_value_is_function (external_func_val)
                && jerry_value_is_constructor (external_func_val));

  res = set_property (global_obj_val, "external", external_func_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (external_func_val);

  // Call 'call_external' function that should call external function created above
  val_call_external = get_property (global_obj_val, "call_external");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_call_external));
  JERRY_ASSERT (jerry_value_is_object (val_call_external));
  res = jerry_call_function (val_call_external, global_obj_val, NULL, 0);
  jerry_release_value (val_call_external);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_string (res));
  sz = jerry_get_string_size (res);
  JERRY_ASSERT (sz == 19);
  sz = jerry_string_to_char_buffer (res, (jerry_char_t *) buffer, sz);
  JERRY_ASSERT (sz == 19);
  jerry_release_value (res);
  JERRY_ASSERT (!strncmp (buffer, "string from handler", (size_t) sz));

  // Create native handler bound function object and set it to 'external_construct' variable
  external_construct_val = jerry_create_external_function (handler_construct);
  JERRY_ASSERT (jerry_value_is_function (external_construct_val)
                && jerry_value_is_constructor (external_construct_val));

  res = set_property (global_obj_val, "external_construct", external_construct_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (res);

  // Call external function created above, as constructor
  args[0] = jerry_create_boolean (true);
  res = jerry_construct_object (external_construct_val, args, 1);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_object (res));
  val_value_field = get_property (res, "value_field");

  // Get 'value_field' of constructed object
  JERRY_ASSERT (!jerry_value_has_error_flag (val_value_field));
  JERRY_ASSERT (jerry_value_is_boolean (val_value_field)
                && jerry_get_boolean_value (val_value_field));
  jerry_release_value (val_value_field);
  jerry_release_value (external_construct_val);

  uintptr_t ptr;
  is_ok = jerry_get_object_native_handle (res, &ptr);
  JERRY_ASSERT (is_ok
                && ptr == (uintptr_t) 0x0012345678abcdefull);

  jerry_release_value (res);

  // Test: Throwing exception from native handler.
  throw_test_handler_val = jerry_create_external_function (handler_throw_test);
  JERRY_ASSERT (jerry_value_is_function (throw_test_handler_val));

  res = set_property (global_obj_val, "throw_test", throw_test_handler_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (res);
  jerry_release_value (throw_test_handler_val);

  val_t = get_property (global_obj_val, "call_throw_test");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_object (val_t));

  res = jerry_call_function (val_t, global_obj_val, NULL, 0);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  jerry_release_value (val_t);
  jerry_release_value (res);

  // Test: Unhandled exception in called function
  val_t = get_property (global_obj_val, "throw_reference_error");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_object (val_t));

  res = jerry_call_function (val_t, global_obj_val, NULL, 0);

  JERRY_ASSERT (jerry_value_has_error_flag (res));
  jerry_release_value (val_t);

  // 'res' should contain exception object
  JERRY_ASSERT (jerry_value_is_object (res));
  jerry_release_value (res);

  // Test: Call of non-function
  obj_val = jerry_create_object ();
  res = jerry_call_function (obj_val, global_obj_val, NULL, 0);
  JERRY_ASSERT (jerry_value_has_error_flag (res));

  // 'res' should contain exception object
  JERRY_ASSERT (jerry_value_is_object (res));
  jerry_release_value (res);

  jerry_release_value (obj_val);

  // Test: Unhandled exception in function called, as constructor
  val_t = get_property (global_obj_val, "throw_reference_error");
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_object (val_t));

  res = jerry_construct_object (val_t, NULL, 0);
  JERRY_ASSERT (jerry_value_has_error_flag (res));
  jerry_release_value (val_t);

  // 'res' should contain exception object
  JERRY_ASSERT (jerry_value_is_object (res));
  jerry_release_value (res);

  // Test: Call of non-function as constructor
  obj_val = jerry_create_object ();
  res = jerry_construct_object (obj_val, NULL, 0);
  JERRY_ASSERT (jerry_value_has_error_flag (res));

  // 'res' should contain exception object
  JERRY_ASSERT (jerry_value_is_object (res));
  jerry_release_value (res);

  jerry_release_value (obj_val);

  // Test: Array Object API
  jerry_value_t array_obj_val = jerry_create_array (10);
  JERRY_ASSERT (jerry_value_is_array (array_obj_val));
  JERRY_ASSERT (jerry_get_array_length (array_obj_val) == 10);

  jerry_value_t v_in = jerry_create_number (10.5);
  jerry_set_property_by_index (array_obj_val, 5, v_in);
  jerry_value_t v_out = jerry_get_property_by_index (array_obj_val, 5);

  JERRY_ASSERT (jerry_value_is_number (v_out)
                && jerry_get_number_value (v_out) == 10.5);

  jerry_release_value (v_in);
  jerry_release_value (v_out);
  jerry_release_value (array_obj_val);

  // Test: init property descriptor
  jerry_property_descriptor_t prop_desc;
  jerry_init_property_descriptor_fields (&prop_desc);
  JERRY_ASSERT (prop_desc.is_value_defined == false);
  JERRY_ASSERT (jerry_value_is_undefined (prop_desc.value));
  JERRY_ASSERT (prop_desc.is_writable_defined == false);
  JERRY_ASSERT (prop_desc.is_writable == false);
  JERRY_ASSERT (prop_desc.is_enumerable_defined == false);
  JERRY_ASSERT (prop_desc.is_enumerable == false);
  JERRY_ASSERT (prop_desc.is_configurable_defined == false);
  JERRY_ASSERT (prop_desc.is_configurable == false);
  JERRY_ASSERT (prop_desc.is_get_defined == false);
  JERRY_ASSERT (jerry_value_is_undefined (prop_desc.getter));
  JERRY_ASSERT (prop_desc.is_set_defined == false);
  JERRY_ASSERT (jerry_value_is_undefined (prop_desc.setter));

  // Test: define own properties
  jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "my_defined_property");
  prop_desc.is_value_defined = true;
  prop_desc.value = jerry_acquire_value (prop_name);
  res = jerry_define_own_property (global_obj_val, prop_name, &prop_desc);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_boolean (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  jerry_release_value (res);
  jerry_free_property_descriptor_fields (&prop_desc);

  // Test: get own property descriptor
  is_ok = jerry_get_own_property_descriptor (global_obj_val, prop_name, &prop_desc);
  JERRY_ASSERT (is_ok);
  JERRY_ASSERT (prop_desc.is_value_defined == true);
  JERRY_ASSERT (jerry_value_is_string (prop_desc.value));
  JERRY_ASSERT (prop_desc.is_writable == false);
  JERRY_ASSERT (prop_desc.is_enumerable == false);
  JERRY_ASSERT (prop_desc.is_configurable == false);
  JERRY_ASSERT (prop_desc.is_get_defined == false);
  JERRY_ASSERT (jerry_value_is_undefined (prop_desc.getter));
  JERRY_ASSERT (prop_desc.is_set_defined == false);
  JERRY_ASSERT (jerry_value_is_undefined (prop_desc.setter));
  jerry_release_value (prop_name);
  jerry_free_property_descriptor_fields (&prop_desc);

  // Test: object keys
  res = jerry_get_object_keys (global_obj_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_array (res));
  jerry_release_value (res);

  // Test: jerry_value_to_primitive
  obj_val = jerry_eval ((jerry_char_t *) "new String ('hello')", 20, false);
  JERRY_ASSERT (!jerry_value_has_error_flag (obj_val));
  JERRY_ASSERT (jerry_value_is_object (obj_val));
  JERRY_ASSERT (!jerry_value_is_string (obj_val));
  prim_val = jerry_value_to_primitive (obj_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (prim_val));
  JERRY_ASSERT (jerry_value_is_string (prim_val));
  jerry_release_value (prim_val);

  // Test: jerry_get_prototype
  proto_val = jerry_get_prototype (obj_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (proto_val));
  JERRY_ASSERT (jerry_value_is_object (proto_val));
  jerry_release_value (obj_val);

  // Test: jerry_set_prototype
  obj_val = jerry_create_object ();
  res = jerry_set_prototype (obj_val, jerry_create_null ());
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_boolean (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));

  res = jerry_set_prototype (obj_val, jerry_create_object ());
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_boolean (res));
  JERRY_ASSERT (jerry_get_boolean_value (res));
  proto_val = jerry_get_prototype (obj_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (proto_val));
  JERRY_ASSERT (jerry_value_is_object (proto_val));
  jerry_release_value (proto_val);
  jerry_release_value (obj_val);

  // Test: eval
  const char *eval_code_src_p = "(function () { return 123; })";
  val_t = jerry_eval ((jerry_char_t *) eval_code_src_p, strlen (eval_code_src_p), true);
  JERRY_ASSERT (!jerry_value_has_error_flag (val_t));
  JERRY_ASSERT (jerry_value_is_object (val_t));
  JERRY_ASSERT (jerry_value_is_function (val_t));

  res = jerry_call_function (val_t, jerry_create_undefined (), NULL, 0);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  JERRY_ASSERT (jerry_value_is_number (res)
                && jerry_get_number_value (res) == 123.0);
  jerry_release_value (res);

  jerry_release_value (val_t);

  // cleanup.
  jerry_release_value (global_obj_val);

  // TEST: run gc.
  jerry_gc ();

  jerry_cleanup ();

  JERRY_ASSERT (test_api_is_free_callback_was_called);

  // External Magic String
  jerry_init (JERRY_INIT_SHOW_OPCODES);

  uint32_t num_magic_string_items = (uint32_t) (sizeof (magic_string_items) / sizeof (jerry_char_ptr_t));
  jerry_register_magic_strings (magic_string_items,
                                num_magic_string_items,
                                magic_string_lengths);

  const char *ms_code_src_p = "var global = {}; var console = [1]; var process = 1;";
  parsed_code_val = jerry_parse ((jerry_char_t *) ms_code_src_p, strlen (ms_code_src_p), false);
  JERRY_ASSERT (!jerry_value_has_error_flag (parsed_code_val));

  res = jerry_run (parsed_code_val);
  JERRY_ASSERT (!jerry_value_has_error_flag (res));
  jerry_release_value (res);
  jerry_release_value (parsed_code_val);

  jerry_cleanup ();

  // Dump / execute snapshot
  // FIXME: support save/load snapshot for optimized parser
  if (false)
  {
    static uint8_t global_mode_snapshot_buffer[1024];
    static uint8_t eval_mode_snapshot_buffer[1024];

    const char *code_to_snapshot_p = "(function () { return 'string from snapshot'; }) ();";

    jerry_init (JERRY_INIT_SHOW_OPCODES);
    size_t global_mode_snapshot_size = jerry_parse_and_save_snapshot ((jerry_char_t *) code_to_snapshot_p,
                                                                      strlen (code_to_snapshot_p),
                                                                      true,
                                                                      false,
                                                                      global_mode_snapshot_buffer,
                                                                      sizeof (global_mode_snapshot_buffer));
    JERRY_ASSERT (global_mode_snapshot_size != 0);
    jerry_cleanup ();

    jerry_init (JERRY_INIT_SHOW_OPCODES);
    size_t eval_mode_snapshot_size = jerry_parse_and_save_snapshot ((jerry_char_t *) code_to_snapshot_p,
                                                                    strlen (code_to_snapshot_p),
                                                                    false,
                                                                    false,
                                                                    eval_mode_snapshot_buffer,
                                                                    sizeof (eval_mode_snapshot_buffer));
    JERRY_ASSERT (eval_mode_snapshot_size != 0);
    jerry_cleanup ();

    jerry_init (JERRY_INIT_SHOW_OPCODES);

    res = jerry_exec_snapshot (global_mode_snapshot_buffer,
                               global_mode_snapshot_size,
                               false);

    JERRY_ASSERT (!jerry_value_has_error_flag (res));
    JERRY_ASSERT (jerry_value_is_undefined (res));
    jerry_release_value (res);

    res = jerry_exec_snapshot (eval_mode_snapshot_buffer,
                               eval_mode_snapshot_size,
                               false);

    JERRY_ASSERT (!jerry_value_has_error_flag (res));
    JERRY_ASSERT (jerry_value_is_string (res));
    sz = jerry_get_string_size (res);
    JERRY_ASSERT (sz == 20);
    sz = jerry_string_to_char_buffer (res, (jerry_char_t *) buffer, sz);
    JERRY_ASSERT (sz == 20);
    jerry_release_value (res);
    JERRY_ASSERT (!strncmp (buffer, "string from snapshot", (size_t) sz));

    jerry_cleanup ();
  }

  return 0;
} /* main */
Example #28
0
int
main (int argc,
      char **argv)
{
  if (argc > JERRY_MAX_COMMAND_LINE_ARGS)
  {
    jerry_port_log (JERRY_LOG_LEVEL_ERROR,
                    "Error: too many command line arguments: %d (JERRY_MAX_COMMAND_LINE_ARGS=%d)\n",
                    argc,
                    JERRY_MAX_COMMAND_LINE_ARGS);

    return JERRY_STANDALONE_EXIT_CODE_FAIL;
  }

  const char *file_names[JERRY_MAX_COMMAND_LINE_ARGS];
  int i;
  int files_counter = 0;

  size_t max_data_bss_size, max_stack_size;
  jerry_get_memory_limits (&max_data_bss_size, &max_stack_size);

  // FIXME:
  //  jrt_set_mem_limits (max_data_bss_size, max_stack_size);

  jerry_init_flag_t flags = JERRY_INIT_EMPTY;

  const char *exec_snapshot_file_names[JERRY_MAX_COMMAND_LINE_ARGS];
  int exec_snapshots_count = 0;

  bool is_parse_only = false;
  bool is_save_snapshot_mode = false;
  bool is_save_snapshot_mode_for_global_or_eval = false;
  const char *save_snapshot_file_name_p = NULL;

  bool is_repl_mode = false;

  for (i = 1; i < argc; i++)
  {
    if (!strcmp ("-h", argv[i]) || !strcmp ("--help", argv[i]))
    {
      print_help (argv[0]);
      return JERRY_STANDALONE_EXIT_CODE_OK;
    }
    else if (!strcmp ("-v", argv[i]) || !strcmp ("--version", argv[i]))
    {
      jerry_port_console ("Version: \t%d.%d\n\n", JERRY_API_MAJOR_VERSION, JERRY_API_MINOR_VERSION);
      return JERRY_STANDALONE_EXIT_CODE_OK;
    }
    else if (!strcmp ("--mem-stats", argv[i]))
    {
      flags |= JERRY_INIT_MEM_STATS;
      jerry_port_default_set_log_level (JERRY_LOG_LEVEL_DEBUG);
    }
    else if (!strcmp ("--mem-stats-separate", argv[i]))
    {
      flags |= JERRY_INIT_MEM_STATS_SEPARATE;
      jerry_port_default_set_log_level (JERRY_LOG_LEVEL_DEBUG);
    }
    else if (!strcmp ("--parse-only", argv[i]))
    {
      is_parse_only = true;
    }
    else if (!strcmp ("--show-opcodes", argv[i]))
    {
      flags |= JERRY_INIT_SHOW_OPCODES;
      jerry_port_default_set_log_level (JERRY_LOG_LEVEL_DEBUG);
    }
    else if (!strcmp ("--show-regexp-opcodes", argv[i]))
    {
      flags |= JERRY_INIT_SHOW_REGEXP_OPCODES;
      jerry_port_default_set_log_level (JERRY_LOG_LEVEL_DEBUG);
    }
    else if (!strcmp ("--save-snapshot-for-global", argv[i])
             || !strcmp ("--save-snapshot-for-eval", argv[i]))
    {
      is_save_snapshot_mode = true;
      is_save_snapshot_mode_for_global_or_eval = !strcmp ("--save-snapshot-for-global", argv[i]);

      if (save_snapshot_file_name_p != NULL)
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: snapshot file name already specified\n");
        print_usage (argv[0]);
        return JERRY_STANDALONE_EXIT_CODE_FAIL;
      }

      if (++i >= argc)
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: no file specified for %s\n", argv[i - 1]);
        print_usage (argv[0]);
        return JERRY_STANDALONE_EXIT_CODE_FAIL;
      }

      save_snapshot_file_name_p = argv[i];
    }
    else if (!strcmp ("--exec-snapshot", argv[i]))
    {
      if (++i >= argc)
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: no file specified for %s\n", argv[i - 1]);
        print_usage (argv[0]);
        return JERRY_STANDALONE_EXIT_CODE_FAIL;
      }

      assert (exec_snapshots_count < JERRY_MAX_COMMAND_LINE_ARGS);
      exec_snapshot_file_names[exec_snapshots_count++] = argv[i];
    }
    else if (!strcmp ("--log-level", argv[i]))
    {
      if (++i >= argc)
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: no level specified for %s\n", argv[i - 1]);
        print_usage (argv[0]);
        return JERRY_STANDALONE_EXIT_CODE_FAIL;
      }

      if (strlen (argv[i]) != 1 || argv[i][0] < '0' || argv[i][0] > '3')
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: wrong format for %s\n", argv[i - 1]);
        print_usage (argv[0]);
        return JERRY_STANDALONE_EXIT_CODE_FAIL;
      }

      jerry_port_default_set_log_level (argv[i][0] - '0');
    }
    else if (!strcmp ("--abort-on-fail", argv[i]))
    {
      jerry_port_default_set_abort_on_fail (true);
    }
    else if (!strncmp ("-", argv[i], 1))
    {
      jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: unrecognized option: %s\n", argv[i]);
      print_usage (argv[0]);
      return JERRY_STANDALONE_EXIT_CODE_FAIL;
    }
    else
    {
      file_names[files_counter++] = argv[i];
    }
  }

  if (is_save_snapshot_mode)
  {
    if (files_counter != 1)
    {
      jerry_port_log (JERRY_LOG_LEVEL_ERROR,
                      "Error: --save-snapshot argument works with exactly one script\n");
      return JERRY_STANDALONE_EXIT_CODE_FAIL;
    }

    if (exec_snapshots_count != 0)
    {
      jerry_port_log (JERRY_LOG_LEVEL_ERROR,
                      "Error: --save-snapshot and --exec-snapshot options can't be passed simultaneously\n");
      return JERRY_STANDALONE_EXIT_CODE_FAIL;
    }
  }

  if (files_counter == 0
      && exec_snapshots_count == 0)
  {
    is_repl_mode = true;
  }

  jerry_init (flags);

  jerry_value_t global_obj_val = jerry_get_global_object ();
  jerry_value_t assert_value = jerry_create_external_function (assert_handler);

  jerry_value_t assert_func_name_val = jerry_create_string ((jerry_char_t *) "assert");
  bool is_assert_added = jerry_set_property (global_obj_val, assert_func_name_val, assert_value);

  jerry_release_value (assert_func_name_val);
  jerry_release_value (assert_value);
  jerry_release_value (global_obj_val);

  if (!is_assert_added)
  {
    jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Warning: failed to register 'assert' method.");
  }

  jerry_value_t ret_value = jerry_create_undefined ();

  for (int i = 0; i < exec_snapshots_count; i++)
  {
    size_t snapshot_size;
    const uint8_t *snapshot_p = read_file (exec_snapshot_file_names[i], &snapshot_size);

    if (snapshot_p == NULL)
    {
      ret_value = jerry_create_error (JERRY_ERROR_COMMON, (jerry_char_t *) "");
    }
    else
    {
      ret_value = jerry_exec_snapshot ((void *) snapshot_p,
                                       snapshot_size,
                                       true);
    }

    if (jerry_value_has_error_flag (ret_value))
    {
      break;
    }
  }

  if (!jerry_value_has_error_flag (ret_value))
  {
    for (int i = 0; i < files_counter; i++)
    {
      size_t source_size;
      const jerry_char_t *source_p = read_file (file_names[i], &source_size);

      if (source_p == NULL)
      {
        ret_value = jerry_create_error (JERRY_ERROR_COMMON, (jerry_char_t *) "");
      }

      if (is_save_snapshot_mode)
      {
        static uint8_t snapshot_save_buffer[ JERRY_BUFFER_SIZE ];

        size_t snapshot_size = jerry_parse_and_save_snapshot ((jerry_char_t *) source_p,
                                                              source_size,
                                                              is_save_snapshot_mode_for_global_or_eval,
                                                              false,
                                                              snapshot_save_buffer,
                                                              JERRY_BUFFER_SIZE);
        if (snapshot_size == 0)
        {
          ret_value = jerry_create_error (JERRY_ERROR_COMMON, (jerry_char_t *) "");
        }
        else
        {
          FILE *snapshot_file_p = fopen (save_snapshot_file_name_p, "w");
          fwrite (snapshot_save_buffer, sizeof (uint8_t), snapshot_size, snapshot_file_p);
          fclose (snapshot_file_p);
        }
      }
      else
      {
        ret_value = jerry_parse (source_p, source_size, false);

        if (!jerry_value_has_error_flag (ret_value) && !is_parse_only)
        {
          jerry_value_t func_val = ret_value;
          ret_value = jerry_run (func_val);
          jerry_release_value (func_val);
        }
      }

      if (jerry_value_has_error_flag (ret_value))
      {
        break;
      }
    }
  }

  if (is_repl_mode)
  {
    const char *prompt = "jerry> ";
    bool is_done = false;

    jerry_value_t global_obj_val = jerry_get_global_object ();
    jerry_value_t print_func_name_val = jerry_create_string ((jerry_char_t *) "print");
    jerry_value_t print_function = jerry_get_property (global_obj_val, print_func_name_val);

    jerry_release_value (print_func_name_val);

    if (jerry_value_has_error_flag (print_function))
    {
      return JERRY_STANDALONE_EXIT_CODE_FAIL;
    }

    if (!jerry_value_is_function (print_function))
    {
      return JERRY_STANDALONE_EXIT_CODE_FAIL;
    }

    while (!is_done)
    {
      uint8_t *source_buffer_tail = buffer;
      size_t len = 0;

      jerry_port_console ("%s", prompt);

      /* Read a line */
      while (true)
      {
        if (fread (source_buffer_tail, 1, 1, stdin) != 1 && len == 0)
        {
          is_done = true;
          break;
        }
        if (*source_buffer_tail == '\n')
        {
          break;
        }
        source_buffer_tail ++;
        len ++;
      }
      *source_buffer_tail = 0;

      if (len > 0)
      {
        /* Evaluate the line */
        jerry_value_t ret_val_eval = jerry_eval (buffer, len, false);

        /* Print return value */
        const jerry_value_t args[] = { ret_val_eval };
        jerry_value_t ret_val_print = jerry_call_function (print_function,
                                                           jerry_create_undefined (),
                                                           args,
                                                           1);

        jerry_release_value (ret_val_print);
        jerry_release_value (ret_val_eval);
      }
    }

    jerry_release_value (global_obj_val);
    jerry_release_value (print_function);
  }

  int ret_code = JERRY_STANDALONE_EXIT_CODE_OK;

  if (jerry_value_has_error_flag (ret_value))
  {
    jerry_value_clear_error_flag (&ret_value);
    jerry_value_t err_str_val = jerry_value_to_string (ret_value);

    jerry_char_t err_str_buf[256];
    jerry_size_t err_str_size = jerry_get_string_size (err_str_val);

    assert (err_str_size < 256);
    jerry_size_t sz = jerry_string_to_char_buffer (err_str_val, err_str_buf, err_str_size);
    assert (sz == err_str_size);
    err_str_buf[err_str_size] = 0;

    jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Script Error: unhandled exception: %s\n", err_str_buf);

    jerry_release_value (err_str_val);

    ret_code = JERRY_STANDALONE_EXIT_CODE_FAIL;
  }

  jerry_release_value (ret_value);
  jerry_cleanup ();

  return ret_code;

} /* main */
Example #29
0
/**
 * Validate the JS arguments and assign them to the native arguments.
 *
 * @return jerry undefined: all validators passed,
 *         jerry error: a validator failed.
 */
jerry_value_t
jerryx_arg_transform_args (const jerry_value_t *js_arg_p, /**< points to the array with JS arguments */
                           const jerry_length_t js_arg_cnt, /**< the count of the `js_arg_p` array */
                           const jerryx_arg_t *c_arg_p, /**< points to the array of validation/transformation steps */
                           jerry_length_t c_arg_cnt) /**< the count of the `c_arg_p` array */
{
  jerry_value_t ret = jerry_create_undefined ();

  jerryx_arg_js_iterator_t iterator =
  {
    .js_arg_p = js_arg_p,
    .js_arg_cnt = js_arg_cnt,
    .js_arg_idx = 0
  };

  for (; c_arg_cnt != 0 && !jerry_value_is_error (ret); c_arg_cnt--, c_arg_p++)
  {
    ret = c_arg_p->func (&iterator, c_arg_p);
  }

  return ret;
} /* jerryx_arg_transform_args */

/**
 * Validate the this value and the JS arguments,
 * and assign them to the native arguments.
 * This function is useful to perform input validation inside external
 * function handlers (see jerry_external_handler_t).
 * @note this_val is processed as the first value, before the array of arguments.
 *
 * @return jerry undefined: all validators passed,
 *         jerry error: a validator failed.
 */
jerry_value_t
jerryx_arg_transform_this_and_args (const jerry_value_t this_val, /**< the this_val for the external function */
                                    const jerry_value_t *js_arg_p, /**< points to the array with JS arguments */
                                    const jerry_length_t js_arg_cnt, /**< the count of the `js_arg_p` array */
                                    const jerryx_arg_t *c_arg_p, /**< points to the array of transformation steps */
                                    jerry_length_t c_arg_cnt) /**< the count of the `c_arg_p` array */
{
  if (c_arg_cnt == 0)
  {
    return jerry_create_undefined ();
  }

  jerryx_arg_js_iterator_t iterator =
  {
    .js_arg_p = &this_val,
    .js_arg_cnt = 1,
    .js_arg_idx = 0
  };

  jerry_value_t ret = c_arg_p->func (&iterator, c_arg_p);

  if (jerry_value_is_error (ret))
  {
    jerry_release_value (ret);

    return jerry_create_error (JERRY_ERROR_TYPE, (jerry_char_t *) "'this' validation failed.");
  }

  return jerryx_arg_transform_args (js_arg_p, js_arg_cnt, c_arg_p + 1, c_arg_cnt - 1);
} /* jerryx_arg_transform_this_and_args */

/**
 * Validate the `obj_val`'s properties,
 * and assign them to the native arguments.
 *
 * @return jerry undefined: all validators passed,
 *         jerry error: a validator failed.
 */
jerry_value_t
jerryx_arg_transform_object_properties (const jerry_value_t obj_val,/**< the JS object */
                                        const jerry_char_t **name_p, /**< property name list of the JS object */
                                        const jerry_length_t name_cnt, /**< count of the name list */
                                        const jerryx_arg_t *c_arg_p, /**< points to the array of transformation steps */
                                        jerry_length_t c_arg_cnt) /**< the count of the `c_arg_p` array */
{
  if (!jerry_value_is_object (obj_val))
  {
    return jerry_create_error (JERRY_ERROR_TYPE, (jerry_char_t *) "Not an object.");
  }

  jerry_value_t prop[name_cnt];

  for (jerry_length_t i = 0; i < name_cnt; i++, name_p++)
  {
    const jerry_value_t name_str = jerry_create_string (*name_p);
    prop[i] = jerry_get_property (obj_val, name_str);
    jerry_release_value (name_str);

    if (jerry_value_is_error (prop[i]))
    {
      for (jerry_length_t j = 0; j < i; j++)
      {
        jerry_release_value (prop[j]);
      }

      return prop[i];
    }
  }

  const jerry_value_t ret = jerryx_arg_transform_args (prop, name_cnt, c_arg_p, c_arg_cnt);

  for (jerry_length_t i = 0; i < name_cnt; i++)
  {
    jerry_release_value (prop[i]);
  }

  return ret;
} /* jerryx_arg_transform_object_properties */

/**
 * Validate the items in the JS array and assign them to the native arguments.
 *
 * @return jerry undefined: all validators passed,
 *         jerry error: a validator failed.
 */
jerry_value_t
jerryx_arg_transform_array (const jerry_value_t array_val, /**< points to the JS array */
                            const jerryx_arg_t *c_arg_p, /**< points to the array of validation/transformation steps */
                            jerry_length_t c_arg_cnt) /**< the count of the `c_arg_p` array */
{
  if (!jerry_value_is_array (array_val))
  {
    return jerry_create_error (JERRY_ERROR_TYPE, (jerry_char_t *) "Not an array.");
  }

  jerry_value_t arr[c_arg_cnt];

  for (jerry_length_t i = 0; i < c_arg_cnt; i++)
  {
    arr[i] = jerry_get_property_by_index (array_val, i);

    if (jerry_value_is_error (arr[i]))
    {
      for (jerry_length_t j = 0; j < i; j++)
      {
        jerry_release_value (arr[j]);
      }

      return arr[i];
    }
  }

  const jerry_value_t ret = jerryx_arg_transform_args (arr, c_arg_cnt, c_arg_p, c_arg_cnt);

  for (jerry_length_t i = 0; i < c_arg_cnt; i++)
  {
    jerry_release_value (arr[i]);
  }

  return ret;
} /* jerryx_arg_transform_array */