transform javascript to opcode using spidermonkey - code-analysis

i am new to spider monkey and want to use it for transform java script file to sequence of byte code.
i get spider monkey and build it in debug mode.
i want to use JS_CompileScript function in jsapi.h to compile javascript code and analysis this to get bytecode , but when in compile below code and run it , i get run time error.
the error is "Unhandled exception at 0x0f55c020 (mozjs185-1.0.dll) in spiderMonkeyTest.exe: 0xC0000005: Access violation reading location 0x00000d4c." and i do not resolve it.
any body can help me to resolve this or introducing other solutions to get byte code from javascript code by using spider monkey ?
// spiderMonkeyTest.cpp : Defines the entry point for the console application.
//
#define XP_WIN
#include <iostream>
#include <fstream>
#include "stdafx.h"
#include "jsapi.h"
#include "jsanalyze.h"
using namespace std;
using namespace js;
static JSClass global_class = { "global",
JSCLASS_NEW_RESOLVE | JSCLASS_GLOBAL_FLAGS,
JS_PropertyStub,
NULL,
JS_PropertyStub,
JS_StrictPropertyStub,
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL,
JSCLASS_NO_OPTIONAL_MEMBERS
};
int _tmain(int argc, _TCHAR* argv[]) {
/* Create a JS runtime. */
JSRuntime *rt = JS_NewRuntime(16L * 1024L * 1024L);
if (rt == NULL)
return 1;
/* Create a context. */
JSContext *cx = JS_NewContext(rt, 8192);
if (cx == NULL)
return 1;
JS_SetOptions(cx, JSOPTION_VAROBJFIX);
JSScript *script;
JSObject *obj;
const char *js = "function a() { var tmp; tmp = 1 + 2; temp = temp * 2; alert(tmp); return 1; }";
obj = JS_CompileScript(cx,JS_GetGlobalObject(cx),js,strlen(js),"code.js",NULL);
script = obj->getScript();
if (script == NULL)
return JS_FALSE; /* compilation error */
js::analyze::Script *sc = new js::analyze::Script();
sc->analyze(cx,script);
JS_DestroyContext(cx);
JS_DestroyRuntime(rt);
/* Shut down the JS engine. */
JS_ShutDown();
return 1;
}

Which version of Spidermonkey are you using? I am using the one that comes with FireFox 10 so the API may be different.
You should create a new global object and initialize it by calling JS_NewCompartmentAndGlobalObject() and JS_InitStandardClasses() before compiling your script :
.....
/*
* Create the global object in a new compartment.
* You always need a global object per context.
*/
global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
if (global == NULL)
return 1;
/*
* Populate the global object with the standard JavaScript
* function and object classes, such as Object, Array, Date.
*/
if (!JS_InitStandardClasses(cx, global))
return 1;
......
Note, the function JS_NewCompartmentAndGlobalObject() is obsolete now, check the latest JSAPI documentation for the version your are using. Your JS_CompileScript() call just try to retrieve a global object which has not been created and probably this causes the exception.

how about using function "SaveCompiled" ? it will save object/op-code (compiled javascript) to file

Related

unresolved symbol pthread_create, first referenced in ./armrtk/src/task.obj

I have been trying to figure this out for a few days now and cannot figure it out. I am using CCS as the IDE and I am working on windows. I am trying to create an RTOS Kernel on a MSP432 and need to use pthreads. I have been able to use pthreads in other examples but I am trying to do my own program and I get this issue when building :
unresolved symbol pthread_create, first referenced in ./armrtk/src/task.obj
I have included the file path into CCS and I cannot use a .cfg file because I am not using XDCTools. I just need help with this and I greatly appreciate it.
I also get a warning:
in pthread_create in TASK.C: #169-D argument of type "void *" is incompatible with parameter of type "void *(*)(void *)"
TASK.H
#ifndef TASK_H
#define TASK_H
#include <pthread.h>
struct task_t {
pthread_t* thread;
int threadCheck;
int state;
};
void *task1(void);
void *task2(void);
struct task_t *create_task(void* functionptr);
void delete_task(void *task);
#endif
TASK.C
#include <task.h>
#include <stdlib.h>
#include <pthread.h>
#define BLOCKED -1
#define READY 0
#define RUNNING 1
int testValue1 = 0;
int testValue2 = 0;
struct task_t *new_task;
pthread_t pntr;
struct task_t *create_task(void* functionptr) {
new_task = malloc(sizeof(struct task_t));
if(!new_task)
return NULL;
//set State of the new thread to ready
new_task->state = 0;
// check to see if pthread is created
**new_task->threadCheck = pthread_create(new_task->thread, NULL, functionptr, NULL);**
if(new_task->threadCheck!= 0){
//thread failed
return NULL;
}
return new_task;
}
void delete_task(void *task) {
if(task != NULL){
free(task);
pthread_exit(NULL);
}
}
The unresolved symbol error is a linker error, not a compiler error. You have failed to link the pthreads library.
With respect to the warning functionptr is a void* where pthread_create() expects a pointer-to-function with signature void fn(void*).
Your task functions have a different signature in any case: void fn(void), so in any event you will need to cast the function pointer in the call to pthread_create() (although you are loosing a useful means of passing information into a task function by omiting the void* argument).
Modify task.h:
typedef void* (*task_t)(void);
struct task_t *create_task( task_t functionptr);
The in task.cpp
new_task->threadCheck = pthread_create( new_task->thread,
NULL,
(void (*)(void *))functionptr,
NULL ) ;
The cast in the pthread_create() call alone would supress the warning, but it bad form to pass a function pointer as a generic void* since it would prevent the compiler warning you if you were to pass anything other then a function pointer of the expected form to to the create_task()`

JNI header missing in Objective-C

I have a file.c in my project which has #include <jni.h> header file. What is the process to include this header file in project or macOS?
Let's say you have following code
#include "jni.h"
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
JavaVMOption options[3];
options[0].optionString = "-Djava.class.path=_HERE_GOES_LOCATION_OF_JNICOOKBOK_/jnicookbook/recipeNo051/target";
vm_args.options = options;
vm_args.ignoreUnrecognized = 0;
vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 1;
int status = JNI_CreateJavaVM (&jvm, (void **) &env, &vm_args);
if (status < 0 || !env) {
printf ("Error - JVM creation failed\n");
return 1;
}
jclass cls_Main = (*env)->FindClass (env, "recipeNo051/Main");
jmethodID method_displayMessage = (*env)->GetStaticMethodID (env, cls_Main, "displayMessage", "()V");
(*env)->CallStaticVoidMethod(env, cls_Main, method_displayMessage);
(*jvm)->DestroyJavaVM( jvm );
}
return 0;
}
in order to run it you will need
location of libjvm.dylib
location of headers
location of compiled Java classes that are called from main.m
Let's start with libs and headers. You have to make sure that following paths are searched for includes (note that I am using jdk-11.0.4):
/Library/Java/JavaVirtualMachines/jdk-11.0.4.jdk/Contents/Home/include
/Library/Java/JavaVirtualMachines/jdk-11.0.4.jdk/Contents/Home/include/darwin/
You have to make sure that following path is added to Library Search Path and to Runpath Search Paths
/Library/Java/JavaVirtualMachines/jdk-11.0.4.jdk/Contents/Home/lib/server
You should have settings like that:
Make sure you are linking your code with libjvm.dylib. Add it inside Build Phases
where you can specify it's location by choosing Add Other...
Run your code, but! Make sure to ignore SIGSEGV before calling method JNI_CreateJavaVM. You can ignore it inside lldb console
(lldb) process handle --pass true --stop false SIGSEGV
After you continue, you can see your JVM instance calling classes from the recipeNo051.
Source code of class: recipeNo051/Main can be found here: https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo051
Update
step by step instructions: http://www.owsiak.org/running-jni-based-code-inside-xcode/
video tutorial: https://youtu.be/WEA-3uI7Y18

Minimal Vulkan example of VkDebugUtilsMessengerEXT usage doesn't output anything?

The following Vulkan program attempts to create an instance and setup a VkDebugUtilsMessengerEXT - but when run it doesn't output anything:
#include <stdlib.h>
#include <stdio.h>
#include <vulkan/vulkan.h>
VkBool32 VKAPI_PTR debug_utils_messenger_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) {
printf("%s", pCallbackData->pMessage);
return VK_FALSE;
}
int main() {
// create instance
VkInstanceCreateInfo instance_create_info = {};
instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
const char* layers[] = {"VK_LAYER_LUNARG_standard_validation"};
instance_create_info.ppEnabledLayerNames = layers;
instance_create_info.enabledLayerCount = 1;
const char* extensions[] = {VK_EXT_DEBUG_UTILS_EXTENSION_NAME};
instance_create_info.enabledExtensionCount = 1;
instance_create_info.ppEnabledExtensionNames = extensions;
VkInstance instance;
if (VK_SUCCESS != vkCreateInstance(&instance_create_info, NULL, &instance))
exit(EXIT_FAILURE);
// load kCreateDebugUtilsMessengerEXT
PFN_vkCreateDebugUtilsMessengerEXT pvkCreateDebugUtilsMessengerEXT =
(PFN_vkCreateDebugUtilsMessengerEXT)
vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (pvkCreateDebugUtilsMessengerEXT == NULL)
exit(EXIT_FAILURE);
// create debug utils messenger
VkDebugUtilsMessengerCreateInfoEXT debug_utils_messenger_create_info = {};
debug_utils_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
debug_utils_messenger_create_info.messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT;
debug_utils_messenger_create_info.messageType =
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT;
debug_utils_messenger_create_info.pfnUserCallback = debug_utils_messenger_callback;
VkDebugUtilsMessengerEXT debug_utils_messenger;
if (VK_SUCCESS != pvkCreateDebugUtilsMessengerEXT(instance, &debug_utils_messenger_create_info, NULL, &debug_utils_messenger))
exit(EXIT_FAILURE);
// destroy instance
vkDestroyInstance(instance, NULL);
}
Why not? I would expect that it outputs some debug messages from the debug_utils_messenger_callback?
Object Tracker does track debug utils objects, but it looks like the layer is only reporting objects belonging to undestroyed device objects at DestroyInstance-time, and debugutils shows up in that list. It should go in a separate Instance object list and get spit out at DestroyInstance time.
A github issue has been submitted: https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/658

Using f_mount to read and write data to text file

In my Application I need to open, read and write data to a text file using the calls f_open, f_read, and f_write.
It is failing to open the .txt file
res = f_open(&f_header.file, file_path, FA_OPEN_EXISTING | FA_WRITE | FA__WRITTEN | FA_READ | FA_CREATE_NEW );
printf("res value after f open %d \n\r",res);
if (res != FR_OK) {
printf("Failed to open %s, error %d\n\r", file_path, res);
}
This is giving error:
FR_NOT_ENABLED, /* (12) The volume has no work area */
For solving this error application program needs to perform f_mount function after each media change to force cleared the filesystem object.
How to use f_mount() call in this application to solve this issue?
I'm not clear about the 2nd parameter.
I added this f_mount(&fs0, "0://", 1); to solve this issue.
Before the f_open call. It is not taking f_mount() call also.
res=f_mount(&fs0,"0://", 1);
res = f_open(&f_header.file, file_path, FA_OPEN_EXISTING | FA_WRITE | FA__WRITTEN | FA_READ | FA_CREATE_NEW );
The code is stopping while run time before the f_mount()
Here is the source code for f_mount which I'm using:
FRESULT f_mount (
FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
const TCHAR* path, /* Logical drive number to be mounted/unmounted */
BYTE opt /* 0:Do not mount (delayed mount), 1:Mount immediately */
)
{
FATFS *cfs;
int vol;
FRESULT res;
const TCHAR *rp = path;
vol = get_ldnumber(&rp);
if (vol < 0) return FR_INVALID_DRIVE;
cfs = FatFs[vol]; /* Pointer to fs object */
if (cfs) {
#if _FS_LOCK
clear_lock(cfs);
#endif
#if _FS_REENTRANT /* Discard sync object of the current volume */
if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
#endif
cfs->fs_type = 0; /* Clear old fs object */
}
if (fs) {
fs->fs_type = 0; /* Clear new fs object */
#if _FS_REENTRANT /* Create sync object for the new volume */
if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
#endif
}
FatFs[vol] = fs; /* Register new fs object */
if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
res = find_volume(&fs, &path, 0); /* Force mounted the volume */
LEAVE_FF(fs, res);
}
The code is not showing any error/warnings at the time of make file.
I'm sure there is no problem with the code.
There is nothing wrong with the code.
Is this some problem related to the memory allocation or out of memory in emmc. What are the possible reason for this behaviour.
According to http://elm-chan.org/fsw/ff/doc/mount.html:
FRESULT f_mount (
FATFS* fs, /* [IN] Filesystem object */
const TCHAR* path, /* [IN] Logical drive number */
BYTE opt /* [IN] Initialization option */
);
Parameters
fs
Pointer to the filesystem object to be registered and cleared. Null pointer unregisters the registered filesystem object.
path
Pointer to the null-terminated string that specifies the logical drive. The string without drive number means the default drive.
opt
Mounting option. 0: Do not mount now (to be mounted on the first access to the volume), 1: Force mounted the volume to check if it is ready to work.
In other words, the second parameter is how you want to refer to this particular filesystem when later working with it.
For example, mounting it like so:
f_mount(&fs0, "0://", 1);
you would then be able to open files like this:
f_open(fp, "0://path/to/file", FA_CREATE_ALWAYS);

PHP Extension return structure

I am working on a PHP extension and wants to let PHP returns a structure. But it always cause core dump. My step is:
./ext_skel --extname=test
./configure --enable-test
in php_test.h, add:
typedef struct mydata {
int m_id;
int m_age;
}MYDATA;
PHP_FUNCTION(wrap_getMydata);`
In test.c, add:
#define MY_RES_NAME "my_resource";
static int my_resource_descriptor;
PHP_FE(wrap_getMydata, NULL)
...
ZEND_MINIT_FUNCTION(test)
{
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
resid = zend_register_list_destructors_ex(NULL, NULL, MY_RES_NAME, module_number);
return SUCCESS;
}
PHP_FUNCTION(test_getMydata)
{
zval* res;
long int a, b;
long int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) {
return;
}
MYDATA objData;
objData.m_id = a;
objData.m_age = b;
ZEND_REGISTER_RESOURCE(res, &objData, resid);
RETURN_RESOURCE(res);
}
add: var_dump(test_getMydata(3,4)) in test.php
then make; make install; ./php test.php, it prints:
Functions available in the test extension:
confirm_wrap_compiled
test_getMydata
Congratulations! You have successfully modified ext/wrap/config.m4. Module wrap is now compiled into PHP.
Segmentation fault (core dumped)
$ gdb ../../bin/php core.23310
Loaded symbols for /home/user1/php/php-5.2.17/lib/php/extensions/no-debug-non-zts-20060613/test.so
#0 0x00000000006388ad in execute (op_array=0x2a9569bd68) at /home/user1/php/php-5.2.17/Zend/zend_vm_execute.h:92
92 if (EX(opline)->handler(&execute_data TSRMLS_CC) > 0) {`
Can someone give some help?
sorry for the bad formatting in the comment - here is my final answer:
i had to rename the extension from test enter code hereto hjtest - everthing else should be pretty much in line with your posted sample.
tl;dr - the problem - and SIGSEGV in your sample is that you are registering a resource to a local variable objData - wich at the end of the function is not reachable anymore - you need to use emalloc to get a piece of dynamic memory - wich holds your MYDATA
as from there you have a resource - bound to some piece of dyn. memory, you need to register a dtor function - so you can release/efree your registered memory.
hope that helps.
to solve the above issue - modifie your resource registration like this:
MYDATA * objData=emalloc(sizeof(MYDATA));
objData->m_id = a;
objData->m_age = b;
ZEND_REGISTER_RESOURCE(return_value, objData, resid);
and add a dtor:
... MINIT
resid = zend_register_list_destructors_ex(resdtor, NULL, MY_RES_NAME, module_number);
and
static void resdtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
MYDATA *res = (MYDATA*)rsrc->ptr;
if (res) {
efree(res);
}
}
for full sample see this GIST: https://gist.github.com/hjanuschka/3ed54e66f017a379cf25