Re: [v8-users] PyMiniRacer, V8, and threading

2024-04-09 Thread Ben Noordhuis
On Tue, Apr 9, 2024 at 2:16 AM Ben Creech  wrote:
>
> Hey folks,
>
> I've recently adopted the PyMiniRacer project; a minimalistic Python/V8 
> bridge originally created by Sqreen. I revamped a lot of things, including 
> the threading model. I was curious if any experts out there want to take a 
> look at what I've done (it's all on the main branch, with the C++ code here.)
>
> Some questions of varying levels of specificity:
>
> Overall threading design:
> I want to run the message loop indefinitely, processing potentially delayed 
> background work, and receiving new work from multiple (Python) threads. It's 
> particularly confusing how to reconcile the fact that I want an 
> always-running message pump loop (to, e.g., run time-delayed async work like 
> setTimeout callbacks) which AFAICT needs the lock, and run new arbitrary 
> tasks coming in from other threads (from Python).
>
> I didn't see an example of this; the two official examples don't show how to 
> run a program indefinitely (thus I'm using d8 as an example of sorts). (Well, 
> I tried to look at Chromium, but I got lost in the enormous git download, 
> heh.) So I sort of copied the model that the d8 tool seems to use for its 
> workers: I construct the Isolate in the same thread that runs the message 
> pump in a loop until shutdown. The message pump thread grabs the Isolate lock 
> and never gives it up. All interaction with the Isolate then has to be done 
> by either (A) posting tasks to the foreground runner or (B) calling 
> v8::Isolate::TerminateExecution.
>
> So the question is, uh, is that a reasonable model?

Pinning isolates to threads? I'd say so. That's how worker_threads in
Node.js are implemented.

> Thread safety of posting and terminating tasks:
> The above brings up a question: is it actually thread-safe to call 
> v8::Platform::GetForegroundTaskRunner(v8::Isolate *) and 
> v8::TaskRunner::PostTask(std::unique_ptr) without the isolate lock, 
> as I'm currently assuming it is? It's not documented as safe! But it seems to 
> be safe upon cursory inspection of the implementation?

Yes, I believe it is.

> Does v8::platform::PumpMessageLoop need, get, or release the Isolate lock?
> Another question from the above: does v8::platform::PumpMessageLoop need the 
> Isolate lock? Does it ever unlock the Isolate lock? I.e., if you grab the 
> Isolate lock and then call it with MessageLoopBehavior::kWaitForWork, it 
> seems to sit around with the lock forever.
>
> I think the answers are: yes the message pump needs the lock, and no it never 
> unlocks it... thus my tentative conclusion is that if you're running the 
> message pump in an indefinite loop in blocking mode, you can't interact with 
> your Isolate on another thread. (Thus the task-posting solution: if you want 
> to interact with your Isolate which has its own infinite message loop, just 
> post a task to the task runner and it will run on the message loop. Makes 
> sense! But it's not written down anywhere AFAICT?)

Technically the answer is probably "PumpMessageLoop doesn't need the
lock/is agnostic" but in practice it does because the tasks it
executes do.

> Is it safe to delete a v8::Persistent without the Isolate lock?
> I'm currently doing some awkward things to transport v8::Persistent deletions 
> onto the Isolate task queue, under the guess that it's not safe to delete 
> things without the lock.

No, that's not safe.

> Is it safe to decref a std::shared_ptr to 0, thus deleting 
> the BackingStore, without the Isolate lock?
> Same as above (but it's even weirder if dropping a std::shared_ptr reference 
> might be thread-unsafe!).

I'm 95% sure the answer is that, yes, it's safe provided your
v8::ArrayBuffer::Allocator implementation is also thread-safe.

> (End of questions.)
>
> Any insight on any of these things would be useful for me, and users of the 
> PyMiniRacer project! It seems to hang together fine under tests, but thread 
> safety is a curious art!
>
> And, while we're here, any other commentary on PyMiniRacer would be very 
> welcome. :)
>
> Thanks,
> Ben Creech

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9EJhGevJRAU%2BaXzt%2BCQrrLAoCnHa0YLAagoiPHSf4Y8Q%40mail.gmail.com.


Re: [v8-users] Re: Error while creating static lib for mac arm and x86 machines

2024-01-05 Thread Ben Noordhuis
On Fri, Jan 5, 2024 at 10:54 AM 'Shivam Gupta' via v8-users
 wrote:
>
> Found a workaround to create static file successfully but I am not sure if 
> this is a valid method:
> I found that removing use_custom_libcxx=false gn args created the static 
> successfully. In the documentation I read that use_custom_libcxx is used to 
> use c++ library present in buildTools. My System c++ library is clang. I am 
> suspecting that is the reason it is failing.
>
> I am unsure what the best practice is here. Should we use use_custom_libcxx 
> or not? Anyhelp would be much appreciated.

There's no right or wrong answer, it depends on your requirements.

V8 bundles its own copy of the C++ standard library for $REASONS. If
you're okay with your program living in its own little pocket universe
(i.e., doesn't interact with code that uses a different stdlib), then
that's a perfectly fine choice.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8W6uGBghJ8xMgu_JjgYzcC-jhtpf7Me9KB%2Btk2swSLmQ%40mail.gmail.com.


Re: [v8-users] startTime of cpu profile

2023-08-02 Thread Ben Noordhuis
On Tue, Aug 1, 2023 at 1:22 PM theratliter theratliter
 wrote:
>
> Thanks, Ben. What does the "ts" field mean ? i can not find this field in cpu 
> profile. I want to find the corresponding samples of the code that was 
> executed at a certain time.

Sorry, I phrased that kind of ambiguously. "ts" is a property of the
"v8.cpu_profiler" trace event that's emitted when you start/stop the
profiler. It doesn't show up in the CPU profile output like
"startTime" does.

If you use event tracing, you should use "ts" because otherwise you
can't sync profiles with traces.

If you don't use event tracing, you can ignore all that. :-)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9kJpxuUkZfsvonKEq-UZaAzKV2fuL9BQ3nt0%2BVM%3DjOBQ%40mail.gmail.com.


Re: [v8-users] startTime of cpu profile

2023-07-31 Thread Ben Noordhuis
On Mon, Jul 31, 2023 at 7:58 PM theratliter theratliter
 wrote:
>
> hello, everyone ! Does anyone know what the `startTime` is in the cpu 
> profile. From the code point of view (v8/src/base/platform/time.cc), it seems 
> that the implementation is different under different systems?

startTime is the system time in microseconds, and yes, the meaning of
"system time" is different across platforms. It's probably best to
treat it as counting from some arbitrary point in the past.

FWIW, I believe you should prefer the "ts" field over "startTime". The
former aligns with the timestamps used in the tracing subsystem.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_-hBd%2BRafwWYQv0-Hd19VddsJnrYY2c8XFLEaMou-jWw%40mail.gmail.com.


Re: [v8-users] Embedding V8 into an existing mainloop

2023-07-08 Thread Ben Noordhuis
On Sat, Jul 8, 2023 at 6:42 AM Daniil Kustov  wrote:
>
> I'm trying to embed V8 into an existing code that already has a mainloop.
>
> As I understand it, script->Run() is executed before the script finishes 
> executing its "main body" (global scope).
>
> The main problem is that in this case my mainloop will hang until the script 
> is executed(My application is single-threaded). Executing scripts in a 
> separate thread also does not look like a good solution, because for each API 
> call of my application from the script, I will have to synchronize the 
> mainloop and the script thread, which in the end can greatly affect the 
> performance and quality of the code.
>
> Also, it would be nice if it was possible to forcibly suspend the execution 
> of JS from the script itself (for example, with the yield function)
>
> Here are the "crutch" solution ideas that are currently available, but they 
> feel terrible:
>
> Creating Fibers for each script, and switching them with the main thread. But 
> in this case, it seems to me that I will break a lot of mechanisms inside the 
> engine.
> Using v8::TryCatch and TerminateExecution.
> Using the v8 debugging API to suspend the script by the "debugger"
>
>
> Also, I tried to write my own implementation v8::Platform, but v8 still 
> executes javascript code synchornously(blocking current thread)

You could call isolate->RequestInterrupt() and run your event loop
from the interrupt callback but then you can't call back into JS code.

If that doesn't work for you, then only option 2 - TryCatch and
TerminateExecution - remains.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_kuPX-sgpH92CmNS%2BsZDijSWQncbXU5bcsCmMfV9njKg%40mail.gmail.com.


Re: [v8-users] Debugging mksnapshot bus error

2023-05-20 Thread Ben Noordhuis
On Fri, May 19, 2023 at 2:25 PM Matt Henkes  wrote:
>
> Thanks for the tip!
> With your help i was able to run mksnapshot through the debugger. Here's my 
> vsCode launch.json file for anyone who comes along after me.
>
> ```
> {
> // Use IntelliSense to learn about possible attributes.
> // Hover to view descriptions of existing attributes.
> // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
> "version": "0.2.0",
> "configurations": [
> {
> "name": "(lldb) Launch mksnapshot",
> "type": "cppdbg",
> "request": "launch",
> "program": "${workspaceFolder}/out/x64.debug/mksnapshot",
> "args": [
> "${workspaceFolder}/snapshot.js",
> "--turbo_instruction_scheduling",
> "--target_os=mac",
> "--target_arch=x64",
> "--embedded_src",
> "${workspaceFolder}/out/x64.debug/gen/embedded.S",
> "--turbo-profiling-input",
> "${workspaceFolder}/tools/builtins-pgo/x64.profile",
> "--embedded_variant",
> "Default",
> "--random-seed",
> "314159265",
> "--startup_blob",
> "snapshot_blob.bin",
> "--no-native-code-counters",
> "--verify-heap"
> ],
> "stopAtEntry": false,
> "cwd": "${fileDirname}",
> "environment": [],
> "externalConsole": false,
> "MIMode": "lldb",
> "sourceFileMap": { "../../": "${workspaceFolder}" }
> }
> ]
> }
>
> ```
>
> I was able to get a callstack at the crash, I'm not sure if it helps, but i'm 
> poking further into it.
>
> [Unknown/Just-In-Time compiled code] (Unknown Source:0)
> mksnapshot!v8::internal::GeneratedCode long, unsigned long, unsigned long, long, unsigned long**>::Call(unsigned 
> long, unsigned long, unsigned long, unsigned long, long, unsigned long**) 
> (/Users/matthenkes/Source/v8-build/v8/src/execution/simulator.h:157)
> mksnapshot!v8::internal::(anonymous 
> namespace)::Invoke(v8::internal::Isolate*, v8::internal::(anonymous 
> namespace)::InvokeParams const&) 
> (/Users/matthenkes/Source/v8-build/v8/src/execution/execution.cc:426)
> mksnapshot!v8::internal::Execution::CallScript(v8::internal::Isolate*, 
> v8::internal::Handle, 
> v8::internal::Handle, 
> v8::internal::Handle) 
> (/Users/matthenkes/Source/v8-build/v8/src/execution/execution.cc:537)
> mksnapshot!v8::Script::Run(v8::Local, v8::Local) 
> (/Users/matthenkes/Source/v8-build/v8/src/api/api.cc:2112)
> mksnapshot!v8::Script::Run(v8::Local) 
> (/Users/matthenkes/Source/v8-build/v8/src/api/api.cc:2040)
> mksnapshot!v8::internal::(anonymous namespace)::RunExtraCode(v8::Isolate*, 
> v8::Local, char const*, char const*) 
> (/Users/matthenkes/Source/v8-build/v8/src/snapshot/snapshot.cc:736)
> mksnapshot!v8::internal::CreateSnapshotDataBlobInternal(v8::SnapshotCreator::FunctionCodeHandling,
>  char const*, v8::Isolate*) 
> (/Users/matthenkes/Source/v8-build/v8/src/snapshot/snapshot.cc:755)
> mksnapshot!(anonymous namespace)::CreateSnapshotDataBlob(v8::Isolate*, char 
> const*) (/Users/matthenkes/Source/v8-build/v8/src/snapshot/mksnapshot.cc:160)
> mksnapshot!main 
> (/Users/matthenkes/Source/v8-build/v8/src/snapshot/mksnapshot.cc:286)
> dyld!start (Unknown Source:0)
>
> In the debugger i am using, lldb, the variables at the time of the crash 
> aren't very useful. They just numbers and addresses when i'd expect them to 
> be an array. (I'm currently a JS dev and haven't looked at C++ in 20 years, 
> so my expectations might be off lol). Anyone know if variables would be more 
> readable if i used GDB instead of LLDB?

I don't expect that to make much of a difference. That line in the
second call frame is where V8 calls into generated machine code and
such crashes are just really, really hard to debug.

The best advice I can give you at this point is to upgrade to a newer
V8 version and see if the problem is fixed. 10.7.71 is almost 9 months
behind.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8S90QQLo_ehnNnPFXEQw2V8LDpcyjVD9SpjR0Bao-_Tg%40mail.gmail.com.


Re: [v8-users] Debugging mksnapshot bus error

2023-05-18 Thread Ben Noordhuis
On Wed, May 17, 2023 at 9:29 PM Matt Henkes  wrote:
>
> Hi all, I'm looking into a mksnapshot bus error which i have logged here: 
> https://bugs.chromium.org/p/v8/issues/detail?id=14007
>
> I've been able to identify the commit that introduced the bug: 
> https://chromium.googlesource.com/v8/v8.git/+/91637c25fcdb199526a7060ceca858aeef16bd3d
>
> But i could really use some advice debugging the issue. What I'd really like 
> is to get a callstack from when the error is throw, but I haven't been 
> successful thus far. I'm building v8 in debug mode and have tried the 
> `--logAll` and `--trace` flags. The logfile doesn't seem to contain anything 
> readable the trace also seems to stop somewhere random, inside the parser 
> map? mksnapshot really has a ton of flags and it's hard to know exactly which 
> ones i should use.
>
> Is it possible to run mksnapshot through a debugger? I haven't been able to 
> find much with my google searches, but i have to assume you can.
>
> I'm new to v8 develop and would appreciate any help.

Yes, you can run it under a debugger but you'll need to pass the exact
same command line arguments that the build scripts do. See the
run_mksnapshot template in BUILD.gn.

You should be able to find the exact stanza in
out/x64.release/toolchain.ninja - it'll be something like "mksnapshot
--turbo_instruction_scheduling --target_os=linux --target_arch=x64"
etc.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8zq1c9JKa4DtJ6D8FCxUPVpm2hcp5E9uNq0TC2Ovcsug%40mail.gmail.com.


Re: [v8-users] v8::Isolate::GetCurrent() - when can it return null

2023-04-05 Thread Ben Noordhuis
On Tue, Apr 4, 2023 at 10:21 PM Bruce MacNaughton
 wrote:
>
> I've written a node extension that works with private data. I see from the 
> function signature that v8::Isolate::GetCurrent() can return NULL, but I 
> don't understand how that's possible, given that my extension is called by 
> JavaScript and has to be running in an isolate.
>
> The v8::Isolate::Current() function has a DCHECK_NOT_NULL, which I infer 
> means that it shouldn't happen. But I don't know when debug checks would be 
> enabled, so that could be a bad inference.
>
> Does it return NULL in specific circumstances, like startup, thread 
> termination, etc.? Can it return

Yes. :-)

A thread "enters" and "exits" (V8 nomenclature) an isolate. Node
normally enters it and doesn't exit until the thread terminates.

v8::Isolate::TryGetCurrent() exists in case you need to handle the
eventuality of no isolate having been entered.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-2qH14kWqYiXkAk%2BywCPBtwMBYwoMGr%3DVnEdGXuJx%2Brw%40mail.gmail.com.


Re: [v8-users] question about V8 Stack roots

2023-04-05 Thread Ben Noordhuis
Can you explain what exactly you find surprising?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-Uayds0T2uPK%2BERKdQmUEcRigy6omw9th71Yy5y%2BDd1A%40mail.gmail.com.


Re: [v8-users] question about V8 Stack roots

2023-04-04 Thread Ben Noordhuis
On Tue, Apr 4, 2023 at 1:41 PM theratliter theratliter
 wrote:
>
> Hi all ! does anyone know what the "Stack root" means ? the memory hold by 
> stack variable ?

They're live references to GC objects in JS and WASM stack frames. A
JS function's local variables are an example.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8REkYnT5_Okz8GbSHqriio%3DA2CO1euLOriqoh0JW%3DoHQ%40mail.gmail.com.


Re: [v8-users] can v8 be run without an OS

2023-03-22 Thread Ben Noordhuis
On Wed, Mar 22, 2023 at 6:24 AM 'Qiaowen Yang' via v8-users
 wrote:
>
> Hi,
>
> I know that building V8 requires a lot of packages, but I am curious whether 
> V8 can be run without an OS. For example, can we use a simulator like gem5 to 
> run V8.
> Thanks for any help.
>
> Yours,
> Qiaowen

Short answer: no

Long(er) answer: V8 depends on the OS for things like memory
allocation and thread creation. You would have to write quite a bit of
glue code to make it work in a "bare metal" (god, I hate that phrase)
environment. V8's build tooling isn't very amenable to such scenarios
either.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_AZ7ng3qqQ6C4RtQtZfAaY6VOzqXoes7vmoq-k6JU3Bw%40mail.gmail.com.


Re: [v8-users] How to compile v8 to Sony PS5?

2023-02-09 Thread Ben Noordhuis
On Thu, Feb 9, 2023 at 11:35 AM Paozi Sha  wrote:
> Gn is used for the construction of v8 project. Can gn build freebsd? There 
> are too few PS materials. I can't find more references.

It could at one time but freebsd is not a supported platform so who
knows. You could use the V8 build from Node.js.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9Ehyb2QdFRLZ8DCmHMrNpXhgY3ggRWKFmVDgGj8HrPRg%40mail.gmail.com.


Re: [v8-users] How to compile v8 to Sony PS5?

2023-02-09 Thread Ben Noordhuis
On Thu, Feb 9, 2023 at 10:57 AM 杨少杰  wrote:
>
> I am a game developer, and I recently encountered a problem. How does the v8 
> engine compile to Sony PS5? Or can you give some suggestions?

The PS5 is a x86_64 machine running a variant of freebsd 12 (or 13?),
right? Untested, but building on freebsd and copying over the library
will probably work.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9rYZUUDg_8PNKiG3LH1TYDHLDDmS7OzacwdDELDvG1Gw%40mail.gmail.com.


Re: [v8-users] Runtime.addBinding to create a MessageChannel pairing?

2023-01-30 Thread Ben Noordhuis
On Sun, Jan 29, 2023 at 4:30 PM guest271314  wrote:
>
> Is it possible to use DevTools Runtime.addBinding to create a MessageChannel 
> pairing between MessagePort in extension ServerWorker and MessagePort created 
> by the function in arbitrary Web page?

No. addBinding adds a single-arg function to the execution context. It
sends a 'bindingCalled' event (plus the string argument) to the
inspector client when called. And that's all it does.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_UvZsrbAvnuowQ%2BrZyR5h8MjrgRTiYNCnyd17QXWZ00Q%40mail.gmail.com.


Re: [v8-users] Compiling with gcov and coverage testing

2023-01-20 Thread Ben Noordhuis
On Thu, Jan 19, 2023 at 11:16 PM TL  wrote:
>
> Hi,
>
> I wonder how to install 'd8' with gcov configuration?
> I understand that there are documents for installing v8 and instructions for 
> using gcov, but I am not sure how to. Mainly, I cannot locate tools/gcov.sh.
>
> If this is not possible, I wonder whether there is a way or tool that I can 
> do coverage testing.
>
> Thank you.

That script was removed in 2018 but you can still find it in the git
history: 
https://github.com/v8/v8/blob/d6f0905fef53d30278452f48e29d45ec4dc03be3/tools/gcov.sh

The option to build with code coverage is v8_code_coverage=true. I
don't know if it's still in working shape but there appears to be a
gcov buildbot so... probably?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9BjUNWC%3DFe1s%3DmNg4hs8Mf62%2BUFYD_7c8hqPE_m_vnZw%40mail.gmail.com.


Re: [v8-users] Getting Errors when building monolith

2023-01-18 Thread Ben Noordhuis
On Wed, Jan 18, 2023 at 8:41 PM Alexandra Wheeler  wrote:
>
> I'm trying to build v8 10.0 on zlinux machine with RHEL 8.0 and gcc version 
> 8.2.1.
>
> The build fails at the following command "ninja -C  out/s390x.lin.release 
> v8_monolith"
>  which gives the follow error:
>
> Running command: ninja -C  out/s390x.lin.release v8_monolith
> ninja: Entering directory `out/s390x.lin.release'
> [8/23] CXX obj/v8_initializers/builtins-call-gen.o
> FAILED: obj/v8_initializers/builtins-call-gen.o
> g++ -MMD -MF obj/v8_initializers/builtins-call-gen.o.d -DUSE_UDEV 
> -DUSE_AURA=1 -DUSE_GLIB=1 -DUSE_OZONE=1 -D_FILE_OFFSET_BITS=64 
> -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D__STDC_CONSTANT_MACROS 
> -D__STDC_FORMAT_MACROS -DNDEBUG -DNVALGRIND -DDYNAMIC_ANNOTATIONS_ENABLED=0 
> -DV8_TYPED_ARRAY_MAX_SIZE_IN_HEAP=64 -DV8_INTL_SUPPORT 
> -DV8_ATOMIC_OBJECT_FIELD_WRITES -DV8_ENABLE_LAZY_SOURCE_POSITIONS 
> -DV8_SHARED_RO_HEAP -DV8_WIN64_UNWINDING_INFO 
> -DV8_ENABLE_REGEXP_INTERPRETER_THREADED_DISPATCH -DV8_ENABLE_WEBASSEMBLY 
> -DV8_ALLOCATION_FOLDING -DV8_ALLOCATION_SITE_TRACKING 
> -DV8_ADVANCED_BIGINT_ALGORITHMS -DV8_DEPRECATION_WARNINGS 
> -DV8_IMMINENT_DEPRECATION_WARNINGS -DV8_TARGET_ARCH_S390 
> -DV8_TARGET_ARCH_S390X -DV8_HAVE_TARGET_OS -DV8_TARGET_OS_LINUX 
> -DU_USING_ICU_NAMESPACE=0 -DU_ENABLE_DYLOAD=0 -DUSE_CHROMIUM_ICU=1 
> -DU_ENABLE_TRACING=1 -DU_ENABLE_RESOURCE_TRACING=0 -DU_STATIC_IMPLEMENTATION 
> -DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC -I../.. -Igen -I../../include 
> -Igen/include -I../../third_party/icu/source/common 
> -I../../third_party/icu/source/i18n -fno-ident -fno-strict-aliasing 
> --param=ssp-buffer-size=4 -fstack-protector -funwind-tables -fPIC -pipe 
> -pthread -m64 -Wno-builtin-macro-redefined -D__DATE__= -D__TIME__= 
> -D__TIMESTAMP__= -Wall -Wno-unused-local-typedefs -Wno-maybe-uninitialized 
> -Wno-deprecated-declarations -Wno-comments -Wno-packed-not-aligned 
> -Wno-missing-field-initializers -Wno-unused-parameter -fno-omit-frame-pointer 
> -g0 -ffp-contract=off -march=z196 -Wno-strict-overflow -Wno-return-type 
> -Wno-int-in-bool-context -O3 -fdata-sections -ffunction-sections 
> -fvisibility=default -std=gnu++17 -fno-aligned-new -Wno-narrowing 
> -Wno-class-memaccess -fno-exceptions -fno-rtti -c 
> ../../src/builtins/builtins-call-gen.cc -o 
> obj/v8_initializers/builtins-call-gen.o
> ../../src/builtins/builtins-call-gen.cc: In instantiation of ‘void 
> v8::internal::CallOrConstructBuiltinsAssembler::CallReceiver(v8::internal::Builtin,
>  v8::internal::TNode, 
> v8::internal::TNode, 
> v8::base::Optional >) [with 
> Descriptor = v8::internal::CallTrampoline_BaselineDescriptor]’:
> ../../src/builtins/builtins-call-gen.cc:81:36:   required from here
> ../../src/builtins/builtins-call-gen.cc:492:14: error: passing ‘const 
> v8::base::Optional >’ as ‘this’ 
> argument discards qualifiers [-fpermissive]
>return *maybe_receiver;
>   ^~~
> In file included from ../../src/compiler/code-assembler.h:17,
>  from ../../src/codegen/code-stub-assembler.h:15,
>  from ../../src/builtins/builtins-call-gen.h:8,
>  from ../../src/builtins/builtins-call-gen.cc:5:
> ../../src/base/optional.h:575:16: note:   in call to ‘constexpr T& 
> v8::base::Optional::operator*() & [with T = 
> v8::internal::TNode]’
>constexpr T& operator*() & {
> ^~~~
> ../../src/builtins/builtins-call-gen.cc: In instantiation of ‘void 
> v8::internal::CallOrConstructBuiltinsAssembler::CallReceiver(v8::internal::Builtin,
>  v8::internal::TNode, 
> v8::internal::TNode, 
> v8::base::Optional >) [with 
> Descriptor = v8::internal::CallTrampoline_Baseline_CompactDescriptor]’:
> ../../src/builtins/builtins-call-gen.cc:480:3:   required from ‘void 
> v8::internal::CallOrConstructBuiltinsAssembler::CallReceiver(v8::internal::Builtin,
>  v8::base::Optional >) [with 
> Descriptor = v8::internal::CallTrampoline_Baseline_CompactDescriptor]’
> ../../src/builtins/builtins-call-gen.cc:72:78:   required from here
> ../../src/builtins/builtins-call-gen.cc:492:14: error: passing ‘const 
> v8::base::Optional >’ as ‘this’ 
> argument discards qualifiers [-fpermissive]
>return *maybe_receiver;
>   ^~~
> In file included from ../../src/compiler/code-assembler.h:17,
>  from ../../src/codegen/code-stub-assembler.h:15,
>  from ../../src/builtins/builtins-call-gen.h:8,
>  from ../../src/builtins/builtins-call-gen.cc:5:
> ../../src/base/optional.h:575:16: note:   in call to ‘constexpr T& 
> v8::base::Optional::operator*() & [with T = 
> v8::internal::TNode]’
>constexpr T& operator*() & {
> ^~~~
> In file included from /usr/include/c++/8/functional:59,
>  from ../../src/codegen/code-stub-assembler.h:8,
>  from ../../src/builtins/builtins-call-gen.h:8,
>  from ../../src/builtins/builtins-call-gen.cc:5:

Re: [v8-users] Re: Resuming use of an Isolate after TerminateExecution

2022-10-27 Thread Ben Noordhuis
On Wed, Oct 26, 2022 at 5:29 AM Jianyong Chen  wrote:
>
> Thanks, Ben.
>
> > Assuming your execution contexts don't interleave (context A can't
> > call functions from context B), then all you have to do is place
> > CancelTerminateExecution calls in the right spots.
>
> Yes, we do not have contexts interleaving(but context switch due to
> async calls).
>
> As to the "right spots" could you please give me more details or
> advice about it? Now I'm planning to `CancelTerminateExecution`
> when the `v8::TryCatch` is `HasTerminated`, which is created before

Yes, that should work. "Right spots" means C++ -> JS calls (ex.
v8::Function::Call) and JS->C++ calls (ex. v8::FunctionTemplate
callbacks.)

> entering js code, And mark the current execution environment as
> terminated so that we can skip Resolve/Reject when async operations
> are completed and thus ensure that no new microtask is generated
> or ran(now we use the auto policy for microtask).
>
> Besides the right spots, I'm also concerned that how the
> per-isolate(shared by all contexts) data are processed when I call
> 'TerminateExecution'. Such as the microtask queue, will the queue be
> cleared up by v8 automatically or I should do it manually?

The microtask queue is a good point. V8 clears it out when microtasks
are about to run but execution is terminating.

However, it clears microtasks for _all_ contexts. Presumably that's
not what you want.

You can run microtasks manually and call CancelTerminateExecution
beforehand but then microtasks from the terminated context still run.

I don't think you can really avoid that unless you control all places
where promises are created, e.g., because you use
`v8::Promise::Resolver` for everything.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9V3Mb%2BpWgXpLbWOchQYB2brhwkOzDQk3RDyTm7GpdkEQ%40mail.gmail.com.


Re: [v8-users] Re: Resuming use of an Isolate after TerminateExecution

2022-10-25 Thread Ben Noordhuis
On Tue, Oct 25, 2022 at 3:41 AM Jianyong Chen  wrote:
>
> I also have these questions and if any v8 experts(or people with
> replated knowledge/experience) see this post please give us some
> information about them.
>
> We are embedding v8 into our HTTP server and creating one isolate
> per thread, which may run multiple JavaScript scripts concurrently
> (in separate contexts).
>
> In case scripts run too long, we use a watchdog thread to kill the
> worker thread, and inside the installed signal handler, we call
> isolate->TerminateExecution to stop the script. Since the isolate
> is running multiple scripts, we just want to kill the one which
> really timed out but preserve others(CancelTerminateExecution?).
>
> Is that possible to achieve? If so, what should I pay attention to?
>
> Any advice will be appreciated!

Yes, that can be made to work. V8 unwinds the JS call stack until C++
code calls isolate->CancelTerminateExecution().

Assuming your execution contexts don't interleave (context A can't
call functions from context B), then all you have to do is place
CancelTerminateExecution calls in the right spots.

If they do interleave, well, you're in for a rough time. No real way
to make that work.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8B-u7GQg%3DP3p%3DXVECM5U6Oc2OrcsPwcc8W-yjTTNFRaw%40mail.gmail.com.


Re: [v8-users] How to implement a Native Mesaging host using d8?

2022-10-22 Thread Ben Noordhuis
On Sat, Oct 22, 2022 at 4:09 PM guest271314  wrote:
>
> I have implemented Native Messaging hosts using QuickJS, Deno, and Node.js 
> where it is possible to read stdin and write to stdout.
>
> How would you go about implementing a Native Messaging host using d8?

I probably wouldn't. :-)

d8 exists to power V8's test suite. It's not really intended as a
standalone application.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_XkTm2ODVwg79qEOCLmo6uEdoTJnxZf_VB6-51A7rY2A%40mail.gmail.com.


Re: [v8-users] V8_COMPRESS_POINTERS flag

2022-10-02 Thread Ben Noordhuis
On Sun, Oct 2, 2022 at 5:49 PM theratliter theratliter
 wrote:
>
> Hi, i compile V8(10.8) with -DV8_COMPRESS_POINTERS, but when i run the code 
> it crashes with the error as follows.
> ```
> Embedder-vs-V8 build configuration mismatch. On embedder side sandbox is 
> DISABLED while on V8 side it's ENABLED.
> ```
> Does anybody know why ? thanks!

Compile your own code with -DV8_COMPRESS_POINTERS to fix that.

Pointer compression changes the layout of objects in memory. Embedder
and engine have to agree on the object layout, otherwise things go
boom.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9He5XYs_9yzFrnL1r9mhQ9aVWObHzuqpz%3DLwCT05-dSA%40mail.gmail.com.


Re: [v8-users] chrome dev tool

2022-10-02 Thread Ben Noordhuis
On Sun, Oct 2, 2022 at 11:48 AM theratliter theratliter
 wrote:
>
> Hi, Ben. I think i misunderstand the dev tools. when i enter ctrl + p and 
> input a js file name, dev tools will emit Debugger.getScriptSource.

Right. I don't know DevTools's code well enough to say for sure but I
expect it loads script sources on demand, not eagerly.

Some of the URLs look kind of funky, by the way. "No"?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-YVHc4v1f4txuu-WcT2JJvSvDXbzfPd%3D1_FANGBKmCpA%40mail.gmail.com.


Re: [v8-users] chrome dev tool

2022-10-01 Thread Ben Noordhuis
On Sat, Oct 1, 2022 at 1:14 AM theratliter theratliter
 wrote:
>
> Hi, i am trying to write an inspector server by V8 inspector APIs, but chrome 
> dev tool do not emit 'Debugger.getScriptSource' request to my inspector 
> server when dev tool get a 'Debugger.scriptParsed' push event. Does anybody 
> know know about this ? Thanks !

Assuming you're using v8-inspector.h, not re-implementing the wire
protocol: you don't normally have to handle getScriptSource requests
yourself, V8 handles them for you.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-ziQdbuMFg7r4c7dmpRE-%2BgLrA0WxHZFB_aD7DWKHHvQ%40mail.gmail.com.


Re: [v8-users] CompileFunctionInContext and async functions

2022-09-16 Thread Ben Noordhuis
On Thu, Sep 15, 2022 at 5:56 PM Liam Goodacre  wrote:
>
> Hello,
>
> Is it possible to have a function compiled with CompileFunctionInContext() 
> marked as an async function?

I don't think so. No way to mark it as a generator (function*) either.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc914kWBjcRo8ypU0qhdkYUt_XxmiyRc1boVg5dV5L8VfQ%40mail.gmail.com.


Re: [v8-users] Re: Is calling C functions in JS directly possible?

2022-05-27 Thread Ben Noordhuis
On Wed, May 25, 2022 at 6:03 AM Patric Lemo  wrote:
>
>
> Problems I met when using fast API calls.
>
> Hit rate:
>
> Whether Fast API can take effect seems to be related to JIT. The JIT was not 
> triggered in a simple test example for the first 8000 ~ 11000 times.
> In a complex project, some high-frequency functions should meet the trigger 
> conditions but fail to trigger in the 20-minute test process.
>
>
> Property functions are not triggered
>
>
> Tested the getter setter method of x / y of `Vector2`, but failed to trigger 
> the corresponding CFunction in a big loop.

Check with --trace_opt or --trace_opt_verbose if the method is getting
optimized (and if not, why not.) Fast API calls only work from
optimized code.

If you need help figuring out the problem, please post your code.

> Questions:
>
>  How to improve the hit rate?
>  Is it possible to trigger CFunction directly?
> Fucntioncallback and CFunction need to be provided at the same time. Can I 
> omit the FunctionCallback?
> Will property callback supportFast API?
>
>
> other:
>
> Provide a mechanism to store the function address in a JS variable, 
> jump(instruction) directly to the function, and ignore the sandbox mechanism?

JS and C++ have different calling conventions and value
representations so no, that can't work. There needs to be a
translation layer somewhere.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_rpcvbAP4tn5kJv8TeyLuRQZNx%2BJPerwAzCGcTBMMt2g%40mail.gmail.com.


Re: [v8-users] [10.0.139.9] Compile error "C2280" with MSVC

2022-05-02 Thread Ben Noordhuis
On Sun, May 1, 2022 at 3:46 PM Kazuya Hiruma  wrote:
>
> I'm guessing what is wrong is /WX flag. I'm not sure how to turn it off.

Try passing `treat_warnings_as_errors=false
fatal_linker_warnings=false` to tools/dev/gm.py

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8fA9B%2BDq%3DcrwsMxGcOeX2WJ_8zi%2BwMexmF8f2ibPHq%2Bw%40mail.gmail.com.


Re: [v8-users] [10.0.139.9] Compile error "C2280" with MSVC

2022-05-01 Thread Ben Noordhuis
On Sun, May 1, 2022 at 3:12 AM Kazuya Hiruma  wrote:
>
> Hi, there.
>
> I'm struggling with building V8 as a DLL on Windows with MSVC.
>
> I got a lot of compiler errors. (I will show it below)
>
> I also found out a same discussion thread but it wasn't a way to fix the 
> problem.
>
> -
>
> [My environment info]
>
> Windows 10
> Visual Studio 2019
> MSVC 14.29.30133
> ninja 1.8.2
>
>
> [GN arguments]
> is_debug = false
> is_clang = false
> is_component_build = true
> target_cpu = "x64"
>
> [Etc]
> V8 version 10.0.139.9
>
> -
>
> The error is below.
>
> [770/3045] CXX obj/torque_generated_definitions/factory.obj
> FAILED: obj/torque_generated_definitions/factory.obj
> ninja -t msvc -e environment.x64 -- "C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64/cl.exe" /c 
> gen/torque-generated/factory.cc 
> /Foobj/torque_generated_definitions/factory.obj /nologo /showIncludes 
> -DUSE_AURA=1 -D_CRT_NONSTDC_NO_WARNINGS -D_WINSOCK_DEPRECATED_NO_WARNINGS 
> -D_HAS_EXCEPTIONS=0 -DCOMPONENT_BUILD -D__STD_C -D_CRT_RAND_S 
> -D_CRT_SECURE_NO_DEPRECATE -D_SCL_SECURE_NO_DEPRECATE -D_ATL_NO_OPENGL 
> -D_WINDOWS -DCERT_CHAIN_PARA_HAS_EXTRA_FIELDS -DPSAPI_VERSION=2 -DWIN32 
> -D_SECURE_ATL -DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP -DWIN32_LEAN_AND_MEAN 
> -DNOMINMAX -D_UNICODE -DUNICODE -DNTDDI_VERSION=NTDDI_WIN10_VB 
> -D_WIN32_WINNT=0x0A00 -DWINVER=0x0A00 -DNDEBUG -DNVALGRIND 
> -DDYNAMIC_ANNOTATIONS_ENABLED=0 -DV8_TYPED_ARRAY_MAX_SIZE_IN_HEAP=64 
> -DV8_INTL_SUPPORT -DV8_USE_EXTERNAL_STARTUP_DATA 
> -DV8_ATOMIC_OBJECT_FIELD_WRITES -DV8_ENABLE_LAZY_SOURCE_POSITIONS 
> -DV8_SHARED_RO_HEAP -DV8_WIN64_UNWINDING_INFO 
> -DV8_ENABLE_REGEXP_INTERPRETER_THREADED_DISPATCH -DV8_SHORT_BUILTIN_CALLS 
> -DV8_EXTERNAL_CODE_SPACE -DV8_ENABLE_SYSTEM_INSTRUMENTATION 
> -DV8_ENABLE_WEBASSEMBLY -DV8_ALLOCATION_FOLDING -DV8_ALLOCATION_SITE_TRACKING 
> -DV8_ADVANCED_BIGINT_ALGORITHMS -DV8_COMPRESS_POINTERS 
> -DV8_COMPRESS_POINTERS_IN_SHARED_CAGE -DV8_31BIT_SMIS_ON_64BIT_ARCH 
> -DV8_DEPRECATION_WARNINGS -DV8_IMMINENT_DEPRECATION_WARNINGS 
> -DCPPGC_CAGED_HEAP -DV8_TARGET_ARCH_X64 -DV8_HAVE_TARGET_OS 
> -DV8_TARGET_OS_WIN -DBUILDING_V8_SHARED -DU_USING_ICU_NAMESPACE=0 
> -DU_ENABLE_DYLOAD=0 -DUSE_CHROMIUM_ICU=1 -DU_ENABLE_TRACING=1 
> -DU_ENABLE_RESOURCE_TRACING=0 -DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE 
> -DUSING_V8_BASE_SHARED -I../.. -Igen -I../../include -Igen/include 
> -I../../third_party/icu/source/common -I../../third_party/icu/source/i18n /Gy 
> /FS /bigobj /utf-8 /Zc:sizedDealloc- /wd4117 /D__DATE__= /D__TIME__= 
> /D__TIMESTAMP__= /WX /wd4244 /Zi /MD /wd4245 /wd4267 /wd4324 /wd4701 /wd4702 
> /wd4703 /wd4709 /wd4714 /wd4715 /wd4718 /wd4723 /wd4724 /wd4800 /wd4506 
> /wd4091 /wd4127 /wd4251 /wd4275 /wd4312 /wd4324 /wd4351 /wd4355 /wd4503 
> /wd4589 /wd4611 /wd4100 /wd4121 /wd4244 /wd4505 /wd4510 /wd4512 /wd4610 
> /wd4838 /wd4995 /wd4996 /wd4456 /wd4457 /wd4458 /wd4459 /wd4200 /wd4201 
> /wd4204 /wd4221 /wd4245 /wd4267 /wd4305 /wd4389 /wd4702 /wd4701 /wd4703 
> /wd4661 /wd4706 /wd4715 /O2 /Ob2 /Oy- /Zc:inline /Gw /std:c++17 
> /Zc:alignedNew- /TP /GR- /Fd"obj/torque_generated_definitions_cc.pdb"
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\xutility(4198): error 
> C2280: 
> 'std::unique_ptr>
>  
> ::unique_ptr>::operator
>  =(const 
> std::unique_ptr>
>  &)': attempting to reference a deleted function
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\memory(3270): note: 
> see declaration of 
> 'std::unique_ptr>::operator
>  ='
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\memory(3270): note: 
> 'std::unique_ptr>
>  
> ::unique_ptr>::operator
>  =(const 
> std::unique_ptr>
>  &)': function was explicitly deleted
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\vector(1175): note: 
> see reference to function template instantiation '_OutIt 
> *std::_Copy_unchecked<_Iter,std::unique_ptr>*>(_InIt,_InIt,_OutIt)'
>  being compiled
> with
> [
> _OutIt=std::unique_ptr>
>  *,
> _Iter=std::unique_ptr>
>  *,
> _InIt=std::unique_ptr>
>  *
> ]
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\vector(1189): note: 
> see reference to function template instantiation 'void 
> std::vector>,std::allocator>>>::_Assign_range<_Iter>(_Iter,_Iter,std::forward_iterator_tag)'
>  being compiled
> with
> [
> _Iter=std::unique_ptr>
>  *
> ]
> C:\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\vector(1189): note: 
> see reference to function template instantiation 'void 
> std::vector>,std::allocator>>>::_Assign_range<_Iter>(_Iter,_Iter,std::forward_iterator_tag)'
>  being compiled
> with
> [
> _Iter=std::unique_ptr>
>  *
> ]

Re: [v8-users] JS Module can't see registered function template.

2021-08-29 Thread Ben Noordhuis
On Sat, Aug 28, 2021 at 9:45 PM Ronald Fenner  wrote:
>
> I'm trying to test a JS Module that creates a new object that's been 
> registered from the C++ side but it fails on evaluation with:
> Reference Error: TestObj is not defined.
>
> I can run a script that does essentially the same thing as the module and 
> it's able to run successfully and trigger the C++ function for the 
> construction of the object.
>
> Here's the test code
>
> v8::HandleScope handleScope(m_Isolate);
> JSContext *jsContext = m_Context.lock().get();
> WeakJSModulesPtr weakJSModules = jsContext->GetModules();
> JSModules *jsModules = weakJSModules.lock().get();
>
> JSModulesTestInternal::TestObject::BuildObjectTemplate(m_Isolate);
>
> const char source[] = R"script(
> let obj = new TestObject();
> )script";
> v8::Local v8Source = JSUtilities::StringToV8(m_Isolate, source);
> EXPECT_FALSE(v8Source.IsEmpty());
>
> v8::TryCatch tryCatch(m_Isolate);
>
> v8::Local script = v8::Script::Compile(jsContext->GetContext(), 
> v8Source).ToLocalChecked();
> script->Run(jsContext->GetContext());
> if (tryCatch.HasCaught())
> {
> std::string error = JSUtilities::GetStackTrace(m_Isolate, tryCatch);
> std::cout << "Script Error: " << error << std::endl;
> ASSERT_TRUE(false);
> }
>
> EXPECT_NE(nullptr, JSModulesTestInternal::constructerCreatedObjectTest);
> JSModulesTestInternal::constructerCreatedObjectTest) = nullptr;
>
> //test that module can't be instantiate cause imported module isn't loaded
> v8::Local root;
> v8::MaybeLocal maybeRoot = jsModules->LoadModule("root.mjs");
> EXPECT_TRUE(maybeRoot.ToLocal());
> ASSERT_FALSE(root.IsEmpty());
>
> EXPECT_TRUE(jsModules->InstantiateModule(root));
>
> EXPECT_TRUE(jsModules->RunModule(root)); // Fails here.
>
> ASSERT_NE(nullptr, JSModulesTestInternal::constructerCreatedObjectTest);
>
> EXPECT_EQ(5, JSModulesTestInternal::constructerCreatedObjectTest->GetValue());
>
> Here's the modules code
> import rootImport from 'sub-dir/rootImport'
>
> let obj = new TestObj();
> obj.value = 5;

You didn't include the actual instantiation and evaluation code so
it's hard to say what's going wrong. Try reducing it to a minimal
demonstration.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc93C2FHo18rHcNMsP%3Da8BH5jk-gDVgj_tGgprS33XyPQg%40mail.gmail.com.


Re: [v8-users] How can I delete an old v8::Context?

2021-08-07 Thread Ben Noordhuis
On Fri, Aug 6, 2021 at 2:41 PM J  wrote:
>
> Using embedded v8, I'm trying to clear the current variables and functions.
>
> I've found that in order to save having to recreate the isolate, which can be 
> quite slow, I can just create a new context from the isolate. However, the 
> old context still exists in memory and its not needed.
>
> How can I delete an old context now that I don't need it?
>
> Example code snippet:
>
> ```
> // Creates a new execution environment containing the built-in
> // functions.
> v8::Local CreateShellContext(v8::Isolate* isolate) {
>   // Create a template for the global object.
>   v8::Local global = v8::ObjectTemplate::New(isolate);
>   // Bind the global 'print' function to the C++ Print callback.
>   global->Set(isolate, "print", v8::FunctionTemplate::New(isolate, Print));
>   // Bind the global 'read' function to the C++ Read callback.
>   global->Set(isolate, "read", v8::FunctionTemplate::New(isolate, Read));
>   // Bind the global 'load' function to the C++ Load callback.
>   global->Set(isolate, "load", v8::FunctionTemplate::New(isolate, Load));
>   // Bind the 'quit' function
>   global->Set(isolate, "quit", v8::FunctionTemplate::New(isolate, Quit));
>   // Bind the 'version' function
>   global->Set(isolate, "version", v8::FunctionTemplate::New(isolate, 
> Version));
>   return v8::Context::New(isolate, NULL, global);
> }
> ```
>
> ```
> v8::Local context = CreateShellContext(isolate);
> if (context.IsEmpty()) {
>   fprintf(stderr, "Error creating context\n");
>   return 1;
> }
> if (run_shell) RunShell(context, platform.get());
> ```

This question comes up every six months or so. If you search the
archives, you can probably find a longer discussion, but the short
answer is that you don't, it gets garbage collected when there are no
more references to it.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_suz7aMZbkfJqYZPSSf-vB11WPkBcyz3BvyVNbPssL3w%40mail.gmail.com.


Re: [v8-users] Can not build v8 with custom toolchain

2021-05-25 Thread Ben Noordhuis
On Tue, May 25, 2021 at 2:55 PM Vadim Plakhtinskiy  wrote:
>
> Hi
> I'm trying to build v8 using the custom toolchain. My gn gen command looks 
> like this:
>
> cd /v/build/v_deps_build/v8-prefix/src/v8-build && /usr/bin/cmake -E env 
> CC=clang CXX=/vectorized/llvm/bin/clang++ LD=vectorized/llvm/bin/lld 
> AR=/usr/bin/ar 
> PKG_CONFIG_PATH=/vectorized/lib64/pkgconfig:/vectorized/share/pkgconfig:/vectorized/lib/pkgconfig
>  "CFLAGS=-fPIC -march=westmere -fuse-ld=lld -mllvm -inline-threshold=2500 -O2 
> -g -DNDEBUG" "CXXFLAGS=-fPIC -march=westmere -fuse-ld=lld -mllvm 
> -inline-threshold=2500 -Wno-unused-lambda-capture 
> -Wno-unused-command-line-argument -stdlib=libc++ -O2 -g -DNDEBUG -std=c++20" 
> "LDFLAGS=-Wl,--build-id=sha1 -L/vectorized/lib -L/vectorized/lib64 
> -stdlib=libc++" /vectorized/gn/gn gen 
> /v/build/v_deps_build/v8-prefix/src/v8-build 
> --root=/v/build/v_deps_build/v8-prefix/src/v8/v8 "--args=v8_monolithic=true 
> is_debug=false clang_use_chrome_plugins=false treat_warnings_as_errors=false 
> use_custom_libcxx=false use_glib=false use_sysroot=false 
> v8_use_external_startup_data=false is_component_build=false 
> v8_enable_pointer_compression=false 
> custom_toolchain=\"//build/toolchain/linux/unbundle:default\" 
> host_toolchain=\"//build/toolchain/linux/unbundle:default\"" && 
> /vectorized/gn/gn desc /v/build/v_deps_build/v8-prefix/src/v8-build 
> --root=/v/build/v_deps_build/v8-prefix/src/v8/v8 //:v8_monolith --tree && 
> /usr/bin/cmake -E touch 
> /v/build/v_deps_build/v8-prefix/src/v8-stamp/v8-configure
>
> When I'm running ninja ninja -C  v8_monolith I'm getting the 
> following error:
>
> [5/1560] ACTION 
> //:generate_bytecode_builtins_list(//build/toolchain/linux/unbundle:default)
> FAILED: gen/builtins-generated/bytecodes-builtins-list.h
> python ../v8/v8/tools/run.py ./bytecode_builtins_list_generator 
> gen/builtins-generated/bytecodes-builtins-list.h
> /bytecode_builtins_list_generator: error while loading shared libraries: 
> libc++.so.1: cannot open shared object file: No such file or directory
> Return code is 127
>
> If it's built with ./llvm/install/bin/clang --stdlib=libc++ then I expect it 
> to link with ./llvm/install/libs/x86_64-unknwon-linux/libc++.so.1 but this is 
> not the case.

You probably need to `export
LD_LIBRARY_PATH=$PWD//llvm/install/libs/x86_64-unknown-linux`
(DYLD_LIBRARY_PATH on macOS) in order for the dynamic linker to look
in the right location.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9MM3Zz3xKzTfhAom8f0NEnZo_j-SCQTZKq4b107adN0w%40mail.gmail.com.


Re: [v8-users] Is it possible to determine the function scope a JSObject was created in?

2021-04-26 Thread Ben Noordhuis
On Fri, Apr 23, 2021 at 4:42 PM Joey Allen  wrote:
>
>
> Hello all,
>
> We are working on a research project and one functionality we are trying to 
> implement is to hook the entry point of a JS function, and then backtrack to 
> determine the scope in which the input parameters for this function were 
> created.
>
> To implement hooking the entry point of a function, we used an approach 
> similar to the --trace flag, and it is working well. However, we are facing 
> issues when implementing the  "backtracking" to determine the creation scope 
> of the input parameters.
>
> To provide an example in what we are trying to achieve, I have provided a 
> sample program below. In this sample program, the goal of our instrumentation 
> will be to hook the send function and eventually learn that the input 
> parameter, data, was created in the sendDatafunction.
>
> Sample Program:
>
> function send(data) {
> console.log(data)
> }
>
> function preSend(data) {
>   send(data)
> }
>
> function sendData() {
>   var data = "input-data"
>   preSend(data)
> }
>
> sendData()
>
> Our Current Approach
>
> Our current approach to determine the creation scope is to iterate the JS 
> call stack, and then access the context for each function. Using the context, 
> we then are calling context.scope_info() to reference the ScopeInfo, which 
> will hopefully provide information related to the variables created in this 
> scope. The intuition behind this approach is based on the comment in 
> `src/objects/contexts.h` which suggests that at runtime a parallel 'context 
> stack' is created.
>
> However, we have found that when walking the Javascript stack, when we check 
> the context of each function, the context() method always returns a 
> NativeContext, which is the same for each function. For example, in the 
> snippet below,  the object returned by it.frame()->context() is the same for 
> every function on the stack for the sample program above.
>
> Isolate* isolate = Isolate::Current();
> JavaScriptFrameIterator it(isolate);
> while (!it.done()) {
> std::cout << "Function: " << it.frame()->function() << std::endl;
> std::cout << "Context: " << it.frame()->context() << std::endl;
> }
>
> Can anyone provide any suggestions on how to access the scope of a specific 
> function, and on the feasibility of this approach? We are also open to other 
> approaches for achieving this.
>
> thanks,
> Joey

Untried, but does it.frame()->function().context() give the expected result?

As a general observation: you can probably use the inspector protocol
for this (see include/js_protocol.pdl, search for CallFrame). I
suspect your current approach won't work for optimized code. The
inspector takes cares of deoptimizing what needs deoptimizing.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-3-G5fgw7seGGHBg3%3DNC9PRw0yNXyBf2_yQTsBi-HL%2Bw%40mail.gmail.com.


Re: [v8-users] When is an internal field destroyed?

2021-04-19 Thread Ben Noordhuis
On Sun, Apr 18, 2021 at 8:13 PM Richard  wrote:
>
> In the following sample code from: 
> https://v8.dev/docs/embed#accessing-dynamic-variables
>
> Point* p = ...;
> v8::Local obj = point_templ->NewInstance();
> obj->SetInternalField(0, v8::External::New(isolate, p));
>
> Is there a way to know when `p` has been finished with? I would like to know 
> when/how to delete the allocated memory.

See v8::Global::SetWeak(), it lets you register a callback that's
invoked when the object is reclaimed by the garbage collector.

Caveat emptor, garbage collection is non-deterministic; it might
simply never run with short-lived scripts.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9XBng33yztwtJNE9_J%3Dd3pWx4JdWrsNFrvWf0ReLmf2g%40mail.gmail.com.


Re: [v8-users] CodeEventHandler accessing string values from worker thread context

2021-02-20 Thread Ben Noordhuis
On Thu, Feb 18, 2021 at 6:36 PM pat m  wrote:
>
> Hello,
>
> I am working on a Node.js module that creates a CodeEventHandler 
> (https://v8docs.nodesource.com/node-14.15/d2/d08/classv8_1_1_code_event_handler.html).
>   I've seen that it's Handle method can be called from outside the main 
> isolate thread, i.e. for parallel garbage collection:
>
> #3  0x7f393a5fb0f3 in 
> codeevents::FnInspectCodeEventHandler::Handle(v8::CodeEvent*) () from 
> /home/ec2-user/module.node
> #4  0x00e43705 in 
> v8::internal::ExternalCodeEventListener::CodeMoveEvent(v8::internal::AbstractCode,
>  v8::internal::AbstractCode) ()
> #5  0x00d5707a in 
> v8::internal::ProfilingMigrationObserver::Move(v8::internal::AllocationSpace, 
> v8::internal::HeapObject, v8::internal::HeapObject, int) ()
> #6  0x00d6d41b in void 
> v8::internal::EvacuateVisitorBase::RawMigrateObject<(v8::internal::EvacuateVisitorBase::MigrationMode)1>(v8::internal::EvacuateVisitorBase*,
>  v8::internal::HeapObject, v8::internal::HeapObject, int, 
> v8::internal::AllocationSpace) ()
> #7  0x00d706df in 
> v8::internal::FullEvacuator::RawEvacuatePage(v8::internal::MemoryChunk*, 
> long*) ()
> #8  0x00d5d17f in 
> v8::internal::Evacuator::EvacuatePage(v8::internal::MemoryChunk*) ()
> #9  0x00d5d67f in 
> v8::internal::PageEvacuationTask::RunInParallel(v8::internal::ItemParallelJob::Task::Runner)
>  ()
> #10 0x00d4f8c5 in v8::internal::ItemParallelJob::Task::RunInternal() 
> ()
> #11 0x00c6c9eb in non-virtual thunk to 
> v8::internal::CancelableTask::Run() ()
> #12 0x00a71405 in node::(anonymous 
> namespace)::PlatformWorkerThread(void*) ()
> #13 0x7f3bd38d440b in start_thread () from /lib64/libpthread.so.0
> #14 0x7f3bd360ef9f in clone () from /lib64/libc.so.6
>
> Is it safe to access the String values returned by GetFunctionName and 
> GetScriptName in this context (i.e. using String.Write)?  Any method to 
> access the underlying characters requires passing the isolate as a parameter, 
> and all of the docs I can find say it's not safe to use the isolate without 
> entering it via Locker.  However that isn't viable in this case as the 
> Node.js main thread locks the isolate on startup, so trying to get a lock on 
> the isolate simply deadlocks the thread.
>
> thanks
> pat

In the case of a CODE_MOVED event, event.script doesn't point to
anything. That field is only valid (and then only sometimes) for
CODE_ADDED events.

I noticed a small bug - V8 doesn't clear unused JitCodeEvent fields
when it emits a CODE_MOVED event - that might be why you get random
crashes instead of nullptr segfaults.

diff --git a/src/logging/log.cc b/src/logging/log.cc
index 7738cab831..94497f6502 100644
--- a/src/logging/log.cc
+++ b/src/logging/log.cc
@@ -751,6 +751,7 @@ void JitLogger::CodeMoveEvent(AbstractCode from,
AbstractCode to) {
   base::MutexGuard guard(_mutex_);

   JitCodeEvent event;
+  memset(static_cast(), 0, sizeof(event));
   event.type = JitCodeEvent::CODE_MOVED;
   event.code_type =
   from.IsCode() ? JitCodeEvent::JIT_CODE : JitCodeEvent::BYTE_CODE;

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-%3D0b2ye9uZsoZcuE0YXEDLcOM65LH4n74psx%3DYHfe45w%40mail.gmail.com.


Re: [v8-users] Handle infinite JS recursion

2021-02-11 Thread Ben Noordhuis
On Thu, Feb 11, 2021 at 12:15 PM 'Vinayaka Kamath' via v8-users
 wrote:
>
> Ben, the Call() is inside a TryCatch, but seems like the call is not 
> returning and just crashing even before the function Call is returning.

V8 makes an educated guess on how much real stack space is available.
It's possible it gets it wrong but you can pass `--stack_size ` to
tell it how much there really is.

(Caveat emptor: that flag only *informs* V8 of the stack size, it
doesn't adjust it.)

If that doesn't fix the issue for you, please post a complete example
+ steps to reproduce the crash.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-OYe79pNz2BhM4gx8G%2BHN0vbUKN5uCssiE-vgxseU0Wg%40mail.gmail.com.


Re: [v8-users] Handle infinite JS recursion

2021-02-11 Thread Ben Noordhuis
On Thu, Feb 11, 2021 at 9:14 AM 'Vinayaka Kamath' via v8-users
 wrote:
>
> Hello All,
>
> I am trying to run a simple function which will hit recursion limit.
>
> function foo(a) {
> return foo(a);
> }
>
> This is simple crashing the v8. I tried using both
> isolate->SetFatalErrorHandler(fatal_error_callback);
> isolate->SetOOMErrorHandler(oom_error_callback);
>
> But neither of them are invoked when the program crashes. Is there any 
> reliable way to make the program recursion free? I am using v8 8.3 BTW
>
> Thanks a lot!

You can catch stack overflow exceptions with a regular v8::TryCatch.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_6mEZo2%3DrLaymrCnACy0ygQn-s-7EeNuCDRwdFPyBAvg%40mail.gmail.com.


Re: [v8-users] Re: [8.7] Compile errors with Visual Studio 2019

2021-02-02 Thread Ben Noordhuis
On Tue, Feb 2, 2021 at 5:46 AM Rodrigo Hernandez
 wrote:
>
> Is there a reason it MUST be 8.7?
>
> I am the current maintainer for Windows builds on VCPKG and Mingw-w64, the 
> VCPKG version is probably exactly what you need, but it currently sits at 8.6.
> I am working on an update to current stable version 8.8, but if it must be 
> 8.7 you may have to see the port and figure it out yourself.
> VCPKG: https://github.com/microsoft/vcpkg
> Direct link to the port: 
> https://github.com/microsoft/vcpkg/tree/master/ports/v8

In that vein: I recently updated to
https://github.com/bnoordhuis/v8-cmake and it's known to build with
Visual Studio (tested through GitHub Action's CI.)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-M93aWhB7egtkOi9YKERVQ23q%2BvmPjf%3Dv99Za7wgR%3D0w%40mail.gmail.com.


Re: [v8-users] Reduce V8 size by eliminating unused features

2021-01-30 Thread Ben Noordhuis
On Fri, Jan 29, 2021 at 9:17 PM Tekman  wrote:
>
> Hi,
>
> Do you have any tips for reducing the size of an embedded V8 by removing 
> unnecessary functionality (such as wasm or worker support)? Size on disk 
> comes to mind since I presume runtime cost is already pay-for-play.
>
> We're looking for a basic ES6 runtime environment that is compact and 
> efficient (with JIT support), without any of the bells & whistles.
>
> Thank you!

Take a look at BUILD.gn, V8 has a veritable zoo of build options. The
two quickest wins are probably v8_enable_lite_mode=true and
v8_enable_i18n_support=false (drops the dependency on ICU, which is
_big_.)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-1pU92-OYo6cYQjxGwi0mr7FS2c2bWkiy5g8Un2v1SKw%40mail.gmail.com.


Re: [v8-users] Return a Weak Persistent to JS

2021-01-19 Thread Ben Noordhuis
On Tue, Jan 19, 2021 at 1:44 PM Vinayaka Kamath
 wrote:
>
> Is there any better way to do it? Basically I am exposing an Object Template 
> to JS through weak persistent handle and it holds internal resources with it. 
> When the object is no longer accessible in the current executing scope of the 
> JS code, I want to free up all the resources held by the instance of Object 
> Template(maybe through some callback).  At first glance it seems like this is 
> what weak handles are meant for.

Well, now you know they're not. :-)

Think of GC as "may reclaim", not "will reclaim", certainly not "will
deterministically reclaim."

If you need determinism, either JS needs to manually release the
resource in try/finally fashion, or you neuter the object after JS is
done with it, callback style:

  withResource(function(resource) {
// do something with |resource|
  }); // <- withResource() neuters |resource| when the callback returns

"Neuter" in this context means "free the internal resource". The
object may still exist in JS land but you clear its internal pointer.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8kGF%2BfHuK8PDPrfkxzWBNevy3kZH9zn0yxHdLouVQOxw%40mail.gmail.com.


Re: [v8-users] Return a Weak Persistent to JS

2021-01-19 Thread Ben Noordhuis
On Tue, Jan 19, 2021 at 12:26 PM Vinayaka Kamath
 wrote:
>
> It seems like the v8 is crashing when I follow this. To add more to what I am 
> trying to do, when the "value" goes out of scope I want it to get garbage 
> collected and in the callback, I am freeing up resources held by the value. I 
> am basically forcing GC using isolate->LowMemoryNotification() only when I am 
> creating a new item that holds the same type of resource as of that of 
> "value". I've ensured that I'm calling LowMemoryNotification() in the same 
> thread as that of persistent->setWeak(). However one of the threads running 
> the process is crashing.

Not a direct answer to your question but it sounds like you're
approaching this wrong. The garbage collector is not a good mechanism
for deterministic resource management.

I also get the impression that you have the wrong idea what "weak"
means here: it's not weak in the sense that it's immediately eligible
for collection, only when there are no strong references (and only
when the garbage collector feels like it - V8's GC is very lazy.)

If your JS code is the functional equivalent of `globalThis.value =
create()`, then you can call LowMemoryNotification() all you want but
it's never going to get collected.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-zG5uYJ1_tSjod5rBJJzrbDqoLkwSoPs9m-1%2BFrOvwhg%40mail.gmail.com.


Re: [v8-users] Clarification on FunctionTemplate / Function / PrototypeTemplate

2021-01-15 Thread Ben Noordhuis
On Fri, Jan 15, 2021 at 1:48 AM Ron Prestenback
 wrote:
>
> Hi Ben, thanks for the reply!  I have worked with C++ for many years but this 
> is my first exposure to javascript.  I'm using the web editor for replying to 
> this, so apologies if the formatting gets messed up :)  I'll try to do inline 
> quotes as well but not sure how that will turn out, so I'll try to space them 
> out to help readability.
>
> I have read over the doc on prototypal inheritance here: 
> https://javascript.info/prototype-inheritance and 
> https://javascript.info/function-prototype  I assume that covers all the 
> important stuff?
>
>> - Constructors return an object
>> - The prototype template is used to configure that object's prototype
>
>
> Why wouldn't the object's prototype be the instance template?  The object 
> returned by the constructor is an instance, right?  And the object's 
> prototype would the "template" the instance was configured from, no?   I'm 
> starting to suspect that "prototype" and "template" have completely different 
> meanings in v8, whereas in standard usage these terms are synonyms.  This is 
> where I get confused, I guess

"Prototype" has a very specific meaning in JS - it's the chain of
objects that are searched to resolve properties that don't exist in
the instance.

Example: var x = o.x;

If o looks like { x: 42 }, then o.x is an instance property, but
otherwise the prototype of o is searched, then the prototoype of the
prototype, and so on. To illustrate:

  var A = { x: 42 };
  var B = { __proto__: A };
  var o = { __proto__: B, y: 1337 };
  var x = o.x; // Searches the chain until it finds A.x
  var y = o.y; // But this lives in the instance

"Template" is just V8 parlance. The template describes the "shape" of
the prototype or instance object.

One way to think about templates is that they're an optimization that
lets V8 allocate the needed space for an object (or prototype)
upfront.

>
>> > What is the difference between a prototype template and an instance 
>> > template?
>> It's the difference between `this` and `this.__proto__`, or:
>>   function F() {
>> this.x = 42;
>>   }
>>   F.prototype.y = 1337;
>
>
> Sorry I'm really trying but I'm not sure how to apply your answer to my 
> question.  In your example, F.prototype would be the same as the __proto__ 
> object for all instances of 'F', right?

Correct.

> If I'm understanding correctly (which is doubtful), in v8 parlance that makes 
> F.prototype the instance template of F, right? If not, which thing is the 
> instance template?

The body of F (the line that sets `this.x = 42`) corresponds with the
instance template.

>> > If I have a constructor function that I want to run when the new objects 
>> > of the class are created, where should that go?
>> FunctionTemplate. Methods are set with FunctionTemplate::PrototypeTemplate().
>> (Technically you can also set them on the instance template but that's
>> kind of pointless.)
>
>
> Oh, why would it be pointless to set a method on an InstanceTemplate?

Because you use the InstanceTemplate for values that are likely
different between different instances of the same class (think: a
Point class with x and y coordinates).

Methods on the other hand don't normally change so those belong on the
prototype.

>> > Depending on the answers to the previous 3, this question may be moot, 
>> > but: Is there any reason to have the same function or property on two or 
>> > more of these "entities"?  FunctionTemplate and Function?  Or Function and 
>> > PrototypeTemplate? etc.  For example, I have some existing code that is 
>> > first setting a property (via Set) on the PrototypeTemplate of the 
>> > FunctionTemplate, then it also sets that same property (with same value) 
>> > on the FunctionTemplate.  What might be the intent here?
>> Probably to make it available as both a method and a class method:
>> o.m() and F.m()
>
>
> OK, that makes sense.  What would the difference be if I set that property on 
> the InstanceTemplate instead?  Or to put another way, why would I ever set 
> something on an InstanceTemplate instead of a PrototypeTemplate?

See above. :-)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9VwnK5f6F%3DD83YFitFdCDRq1PwX76A7uoUxfecSgBqWg%40mail.gmail.com.


Re: [v8-users] Clarification on FunctionTemplate / Function / PrototypeTemplate

2021-01-14 Thread Ben Noordhuis
Replies inline, hope it's useful to you. I'll assume you're familiar
with prototypical inheritance in JS but let me know if you need more
details.

On Thu, Jan 14, 2021 at 9:42 PM Ron Prestenback
 wrote:
>
> Hello everyone,
>
> I've read a lot of information about FunctionTemplate / Function / 
> PrototypeTemplate / InstanceTemplate, but some details are still not clicking 
> for me.  I feel like maybe there is a gap in the documentation that I hope 
> the answers to these questions can help fill:
>
> (FWIW, I'm creating a two-way association between C++ and javascript objects)
>
> The documentation for FunctionTemplate.PrototypeTemplate says it's the 
> "template used to create the prototype object of the function created by this 
> template".  But what is the role of a "prototype object" for a function?  I 
> understand the concept of a "prototype" for an object, but not a function.  
> From what I understand, the new object will already inherit all 
> properties/methods defined on the Function and FunctionTemplate, so what's 
> the prototype object needed for?  And if there's only one prototype object, 
> why do we need a template for it?

- JS functions can be invoked as constructors with the `new` keyword

- Constructors return an object

- The prototype template is used to configure that object's prototype

> What is the difference between a prototype template and an instance template?

It's the difference between `this` and `this.__proto__`, or:

  function F() {
this.x = 42;
  }
  F.prototype.y = 1337;

> What is the difference if I put a property on the FunctionTemplate, the 
> Function, the PrototypeTemplate or the InstanceTemplate?  What should I be 
> taking into account when deciding where to put the property?

Setting properties on the first two is like setting properties on the
JS function object:

  function f() {}
  f.x = 42;

The last two are for construct calls: new F()

> Should I use the same logic for functions/methods as well?  Or are there 
> different considerations for functions?

I don't understand the question, I'm afraid.

> If I have a constructor function that I want to run when the new objects of 
> the class are created, where should that go?

FunctionTemplate. Methods are set with FunctionTemplate::PrototypeTemplate().

(Technically you can also set them on the instance template but that's
kind of pointless.)

> Depending on the answers to the previous 3, this question may be moot, but: 
> Is there any reason to have the same function or property on two or more of 
> these "entities"?  FunctionTemplate and Function?  Or Function and 
> PrototypeTemplate? etc.  For example, I have some existing code that is first 
> setting a property (via Set) on the PrototypeTemplate of the 
> FunctionTemplate, then it also sets that same property (with same value) on 
> the FunctionTemplate.  What might be the intent here?

Probably to make it available as both a method and a class method:
o.m() and F.m()

> I've seen code that calls RemovePrototype on the FunctionTemplate (or maybe 
> the FunctionI'm not sure).  For what reason would you do this?

For the same reason you create prototype-less objects with `{
__proto__: null }` or `Object.create(null)` - usually to avoid
prototype pollution / being able to use objects as plain dictionaries.

HTH!

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_z2XAKDhCxevHBURhKt8u0FaBeakqDApFpdF%3DBCgu3Tg%40mail.gmail.com.


Re: [v8-users] External UTF-8 String

2021-01-12 Thread Ben Noordhuis
On Wed, Jan 13, 2021 at 2:32 AM Tekman  wrote:
>
> Hi,
>
> What is the most efficient way to compile a (large) script that is being 
> passed in as an UTF-8 char buffer?
>
> The ExternalOwningOneByteStringResource is really nice for ASCII buffers, but 
> it looks like for UTF-8 we need to copy the entire contents and covert with 
> NewFromUtf8. It also looks like this memory (converted script source) sticks 
> around for the lifetime of the Isolate.
>
> For really large bundles, it's a waste to keep 2 copies of the script source 
> in memory; are there any optimizations / alternatives to consider?
>
> How feasible would it be to create something like 
> ExternalOwningUTF8StringResource?
>
> Thank you!

There is no way around the conversion. One way or another, you're
going to have two copies, because V8 doesn't use UTF-8 internally. JS
strings are either one-byte or two-byte. V8 does the UTF-8 conversion
at the edges.

The way I solved it in Node.js is by storing the built-in scripts as a
ExternalOneByteStringResource when they're Latin-1, and
ExternalStringResource (two-byte) otherwise.

It's not great for big scripts because approximately half of that
two-byte memory is zero, but on the flip side, it's in read-only
memory and doesn't count towards the JS heap limit.

If you're bundling scripts into your executable and you're worried
about executable size, one approach is to store the sources compressed
and decompress-and-stream them using ScriptCompiler::StartStreaming().
The uncompressed script source stays around for the lifetime of the
script, however.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8_Voz06%2BLjFaKacZ%3Ds47WUEbLjTLcxrfxCj9eiytwayA%40mail.gmail.com.


Re: [v8-users] Re: [v8-google3] Re: Question - Is it possible as the embedder of V8 engine to call an async function directly and await the result?

2021-01-12 Thread Ben Noordhuis
On Tue, Jan 12, 2021 at 2:25 PM 'Andreas Haas' via v8-users
 wrote:
>
> +v8-users
>
> On Tue, Jan 12, 2021 at 2:23 PM Andreas Haas  wrote:
>>
>> Hi All,
>>
>> We were able to minimize the issue further. The problem is that the result 
>> of the script is a promise. Already the script
>>
>> new Promise((res, rej) => {});
>>
>> hangs (thanks Camillo). The problem could be a missing MicroTasksScope, but 
>> we still have to verify that.
>>
>> Cheers, Andreas
>>
>>
>> On Tue, Jan 12, 2021 at 8:25 AM Marja Hölttä  wrote:
>>>
>>> Hi,
>>>
>>> Top-level await only works for modules; assuming your scripts are not 
>>> modules, so that's not applicable for you.
>>>
>>> Didn't ahaas@ implement an API for checking whether there's a pending task, 
>>> so that you could spin the event loop while there's one?
>>>
>>>
>>> On Mon, Jan 11, 2021 at 5:30 PM Maitri Shastri  
>>> wrote:

 +V8 Google3

 On Mon, Jan 11, 2021 at 9:59 PM Maitri Shastri  
 wrote:
>
> Hi All,
> Apps Script (script.google.com) uses Chrome V8 execution engine. Recently 
> we encountered a bug (http://b/176740430) where the user called an async 
> function directly and the script timed out. Is it possible as the 
> embedder to call an async function and await the result?
> Executed it in chrome browser - and the linked snippet didnt time out 
> there. +Andreas Haas pointed me to a public documentation.

new Promise((res, rej) => {}) won't ever resolve. It's not that you
can't await it (there are several ways of doing that) but it's never
going to complete.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9iABFjfs15b7b2fUFrnJJ1VYm3iV-zzwaOdQM248cdWA%40mail.gmail.com.


Re: [v8-users] Fastest Way to check if v8::Local is JSON serialisable or not

2021-01-04 Thread Ben Noordhuis
On Mon, Jan 4, 2021 at 7:06 AM Vinayaka Kamath
 wrote:
>
> Hello All,
>
> I am looking for the fastest way to check if a v8::Local is JSON 
> serialisable or not.
>
> Some negative cases are: undefined, {"foo": undefined}, Object({ })
>
> Thanks!

Simply trying to serialize it is really the only way from a
correctness perspective.

Objects can have .toJSON() methods (IOW, can execute arbitrary code
during serialization) so there is really no way to know what the
serialized object graph looks like until you try it.

By the way, all the negative cases you mention are in fact valid
inputs, they all produce an output when you pass them to
JSON.stringify().

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8L3xcXha88MTwPZsMSRyHaxr9WnOdHPXNjSU5rbSX3fA%40mail.gmail.com.


Re: [v8-users] Re: Trying to beat V8's regex engine with just JS

2020-12-20 Thread Ben Noordhuis
On Fri, Dec 18, 2020 at 5:37 AM J Decker  wrote:
>
> https://swtch.com/~rsc/regexp/regexp1.html ?

That page describes linear-time regular expressions but JS-compatible
regex engines must also support exponential-time backtracking.

As an interesting aside: V8 recently grew a
--enable-experimental-regexp-engine flag that enables /pattern/l ('l'
for 'linear time'), see
https://bugs.chromium.org/p/v8/issues/detail?id=10765 for details. I'm
pretty excited about it, it blocks off a whole class of catastrophic
backtracking bugs.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-cd%3DXwF%2BhhCHNiq1xA%3DOZjY3yeztWz9CH6xMBS4FpmdQ%40mail.gmail.com.


Re: [v8-users] GC stack trace

2020-12-15 Thread Ben Noordhuis
On Tue, Dec 15, 2020 at 9:56 AM Vinayaka Kamath
 wrote:
>
> Hello All,
>
> The project that I am working on embeds v8 in it. One of the users reported 
> seeing the following trace in the log files.
>
>
> 2020-12-01T04:48:31.912-08:00 [INFO] "Starting Function for:" 
> "config::sfdc::accounts"
> 2020-12-01T04:48:31.912-08:00 [INFO] "Fetching list of:" "SFDC::accounts"
> 2020-12-01T04:48:31.950-08:00 [INFO] "Fetching SFDC Objects: " "accounts"
> 2020-12-01T04:54:27.535-08:00 [INFO] "Fetch SFDC (curl) response status:" 200 
> "/ #Objects:" 22179
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO] <--- Last few GCs --->
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO] [5463:0x7f2af005c020] 774469 ms: 
> Mark-sweep 1110.6 (1264.9) -> 1110.6 (1210.4) MB, 497.6 / 0.0 ms (average mu 
> = 0.778, current mu = 0.000) last resort GC in old space requested
> 2020-12-01T04:54:43.716-08:00 [INFO] [5463:0x7f2af005c020] 775228 ms: 
> Mark-sweep 1110.6 (1210.4) -> 1110.6 (1196.9) MB, 758.3 / 0.0 ms (average mu 
> = 0.616, current mu = 0.000) last resort GC in old space requested
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO] <--- JS stacktrace --->
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO]  JS stack trace 
> =
> 2020-12-01T04:54:43.716-08:00 [INFO]
> 2020-12-01T04:54:43.716-08:00 [INFO] 0: ExitFrame [pc: 0x7f2b037168ae]
> 2020-12-01T04:54:43.716-08:00 [INFO] Security context: 0x32a0fa3096b9 
> 
> 2020-12-01T04:54:43.716-08:00 [INFO] 1: FetchObjects_SFDC(aka 
> FetchObjects_SFDC) [0x32a0fa30ea89] [Data_Ingestion.js:324] 
> [bytecode=0x4ef5172bd09 offset=348](this=0x125eac5825a1 
> ,0x19c460402291 )
> 2020-12-01T04:54:43.716-08:00 [INFO] 2: OnUpdate [0x32a0fa30e951] 
> [Data_Ingestion.js:64] [bytecode=0x4ef5172b1e9 
> offset=281](this=0x32a0fa30fd81 ,0x19c460402291  ...
> 2020-12-01T04:54:43.716-08:00 [INFO]
>
> I do not have much information on what the user was trying to do here. Can 
> someone elaborate on when do we generally see GC traces like these?
>
> Thanks

The what is that V8 ran out of JS heap memory, the why I can't tell -
maybe FetchObjects_SFDC() allocates a lot, maybe there's a memory leak
in the JS code somewhere.

The default heap limit is approx. 1.4 GB on 64 bits systems. You can
change it with the --max_heap_size= flag, where n is in megabytes.

There's also --max_old_space_size=, that's an older flag mentioned
in many blog posts. It works pretty much the same.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc80C0mwx09Yb7Yamv7cb3S1xUxtr%3DV7JSishQKHPU4XaA%40mail.gmail.com.


Re: [v8-users] v8::ScriptOrigin line/column offset

2020-11-11 Thread Ben Noordhuis
On Wed, Nov 11, 2020 at 9:26 PM Bit Cortex  wrote:
>
> Hello!
>
> Could someone describe the purpose of the line and column offset properties 
> of v8::ScriptOrigin? What effect do nonzero values have?
>
> Thanks!

I believe they're intended to offset IIFEs[1] and other wrappers that
embedders may want to add around the user's script code.

[https://en.wikipedia.org/wiki/Immediately-invoked_function_expression]

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_LRMLRc4Pg2h-OvF%3D_REN8Ua8ws5qMUzbraNRhxhLkCA%40mail.gmail.com.


Re: [v8-users] how to create a Persistent handle cache?

2020-11-10 Thread Ben Noordhuis
On Tue, Nov 10, 2020 at 4:54 AM jres...@gmail.com  wrote:
>
> I would like to cache Persistent handles in such a way that I can retrieve 
> the same Persistent instance given the identical JS object, i.e. imagine a 
> function like so:
>
> Persistent GetPersistentForObject(Local obj)
> {
>// If we have already created a Persistent for obj, find and return it.
>// Otherwise, create and return a Persistent for obj and cache it for
>// future calls.
> }
>
> The obvious thought is to store the Persistent handles in a map of some kind, 
> but what to use as the key? I assume it would not be possible to actually use 
> Local handles as keys in a map that outlives the current HandleScope.
>
> One thought I had was to assign a unique integer to the object using 
> obj.SetPrivate(...), and use that as the key, but SetPrivate is documented as 
> experimental, which is discouraging.
>
> Is there an easier way to achieve what I'm trying to do? I feel like I may be 
> missing something obvious...
>
> Jonathan

A hashmap should work if you observe the following;

1. Use `v8::Object::GetIdentityHash()` to compute the hash key.
2. Use `Persistent::operator==()` to detect duplicates (also has an
overload that compares against a Local)

I.e., step 1 is to find the right bucket and step 2 is to find out if
that bucket already contains the object.

Using just the identity hash isn't sufficient, see [1] and [2] for discussion.

Caveat: use `v8::Value::SameValue()` - not `Persistent::operator==()`
- if you also store primitives (numbers, strings, etc.)

[1] https://github.com/denoland/deno/pull/7946#discussion_r504192165
[2] https://github.com/denoland/deno/issues/7969

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-%3DihgyFyqe3r4_Nx0-RtWgS6mNrF7GqTap3HoQzbDZ2g%40mail.gmail.com.


Re: [v8-users] Re: Upgrading v8 from 7.4 to 8.5

2020-11-03 Thread Ben Noordhuis
On Tue, Nov 3, 2020 at 9:56 AM Vinayaka Kamath
 wrote:
> While upgrading the v8 version -- I have replaced 
> platform->CallOnForegroundThread  with platform->CallOnWorkerThread. Could 
> the "Fatal error in HandleScope::HandleScope # Entering the V8 API without 
> proper locking in place" happen because of that?

The task calls into V8? Then yes, that's almost certainly it.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-ky9WN6K4L%3DZudFTETTu9%3DWohY8N2nWsYtEDdqN%2B%3DY4w%40mail.gmail.com.


Re: [v8-users] Re: Integrating your personal changes as a dependency into V8

2020-10-28 Thread Ben Noordhuis
On Wed, Oct 28, 2020 at 5:02 AM Shiv Shankar  wrote:
>
> The best way to do this is use Git Patch tool. Create the patch files for 
> each changed file. Automate the build process in such a way that after 
> fetting V8 code, it will get your patch filesfrom your own repo and apply the 
> patches on the source files.
> Thanks,
> Shiv

I second this suggestion. You can crib from
https://github.com/bnoordhuis/v8-cmake - the update_v8.py script
updates to the HEAD of the release branch listed in update_v8.json and
applies everything in the patches/ directory.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8%2B5DtOtuM9icvygU7-05jnu1SrCoNhF5ZPAFDtkfTyHw%40mail.gmail.com.


Re: [v8-users] Reinterpret casting a v8::Persistent to a v8::Local

2020-10-13 Thread Ben Noordhuis
On Tue, Oct 13, 2020 at 3:37 PM Elling B  wrote:
>
> I found this helper method in a tutorial a couple of days ago.
>
> It reinterpret casts a v8::Persistent to a v8::Local, with the intended use 
> of calling V8 API functions that require a local handle to a context, without 
> actually having to create a new v8::Local each time:
>
> template 
> inline v8::Local ToLocal(const v8::Persistent& persistent)
> {
>   return 
> *reinterpret_cast*>(const_cast*>());
> }
>
> I'm new to V8, so I find myself wondering if it's safe or not. Or if it can 
> be safe in some cases.

Full disclosure: that StrongPersistentToLocal() helper from the
article is my code. I introduced that trick in the Node.js code base
years ago and looks like people copied it. Mea culpa. :broken_smile:

So, it works, but it's not particularly safe. Caveats:

- don't use it on weakly persistent handles, only strong ones, and

- don't call .Reset() while the Local is still in use

Node.js (ab)uses it for performance reasons but most of the time you
should just use `Local::New(isolate, persistent)`.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8QawY_UjnM_3CciinG6yMN7Q%2BD%2BjbVFeGWsJ6Caxj8mA%40mail.gmail.com.


Re: [v8-users] Getting unstable builds of V8 under Mac OS

2020-10-12 Thread Ben Noordhuis
On Mon, Oct 12, 2020 at 2:38 AM Cameron Caturria
 wrote:
>
> Hi,
> I have been trying for some time to build a working V8 static library
> under Mac OS with limited success. I can get it to build, but the
> result is unstable.
> I have successfully setup depot-tools, added it to my $PATH, fetched
> V8 and checked out the desired version (I selected version 8.1.307,
> since this is the version that ships with the latest stable Node.js).
> If I use the one step build process after gclient sync:
> Tools/dev/gm.py x64.release
> The result is a build that doesn’t work at all (v8::V8::Initialize()
> never returns, program hangs).
> If I add use_custom_libcxx to build arguments as suggested by this
> related Stack Overflow question:
> https://stackoverflow.com/questions/62250913/cross-compiling-v8-for-arm-hello-world-hangs-during-initialize
> I get a somewhat usable build with some stability issues.
> Specifically, it will crash inside of all error object constructors
> (v8::Exception::RangeError, v8::Exception::TypeError etc).
> The v8_shell sample application that builds alongside V8 works as it
> should, but if I build it myself it crashes after evaluating every
> line.
> I am new to V8, and the documentation is anything but beginner
> friendly. In addition to the embedding guide, I am mostly relying on
> the API reference made available by nodesource.com.
> I am using the following build args:
>
> is_component_build = false
> is_debug = false
> target_cpu = "x64"
> use_goma = false
> goma_dir = "None"
> v8_enable_backtrace = true
> v8_enable_disassembler = true
> v8_enable_object_print = true
> v8_enable_verify_heap = true
> use_custom_libcxx=false
> I am using the default Clang which ships with Xcode:
>
> Apple clang version 11.0.0 (clang-1100.0.33.12)
> Target: x86_64-apple-darwin19.6.0
> Thread model: posix
> InstalledDir: 
> /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
>
> I am using the following compiler and linker flags to build the
> shell.cc example:
> g++ -O3 -std=c++0x ./shell.cc -I/usr/local/include/v8 -lwee8
> -lv8_libbase -lv8_libplatform -pthreads -o v8_shell
>
> A nudge in the right direction would be greatly appreciated.
> Thanks in advance.

There are a couple of preprocessor flags (the -DV8_OPTION_NAME flags
you see in the build output) that affect V8's ABI, notably
V8_COMPRESS_POINTERS and V8_31BIT_SMIS_ON_64BIT_ARCH, and perhaps
V8_ENABLE_CHECKS too.

Compiling the shell should be done with the exact same flags as the V8 build.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_jNB%2BD%3Dnku7AMBNt9TX79_m2u-fq8HDkhxAbte658BXQ%40mail.gmail.com.


Re: [v8-users] Recovering a FunctionTemplate (or how to ->Inherit from one you've lost the handle to?)

2020-10-11 Thread Ben Noordhuis
On Sat, Oct 10, 2020 at 10:44 PM Rodrigo Hernandez
 wrote:
>
> Hello,
>
> So, suppose I am wrapping a C++ class around a JS constructor, I've already 
> created and initialized the isolate, created and initialized a context, I 
> have the FunctionTemplate for the constructor and I have instantiated the 
> function and I can call it from Js as x() or new X(),
> all this is fine, the function template context is finished and the handle 
> lost.
>
> But then I want to create another wrapped object for a class that inherits 
> from the first one.
> Is there a way to retrieve the base class FunctionTemplate so in the child 
> class I can call child->Inherit(base)?
>
> Is there another way of doing this?
>
> Right now I am keeping a C++ unordered_map of isolate to persistent handle to 
> function templates, and that works, but is that the only option?
>
> Thanks!

It's not the only option but it's a pretty good solution. Less optimal
solutions:

- store them in the snapshot with SnapshotCreator::AddData() (but you
can only retrieve it once)
- scan the heap for them with Isolate::VisitHandlesWithClassIds().

No doubt there are more ways to stow them away somewhere.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8KoF_a6N9PQdH%2BmAoemE4Eg5PjjfePmWNYn_Df731SLA%40mail.gmail.com.


Re: [v8-users] Array splice is not optimized when Array.prototype has been altered in v8 7.1+

2020-09-24 Thread Ben Noordhuis
On Thu, Sep 24, 2020 at 11:39 AM Guillaume Grossetie
 wrote:
>
> Thanks for your answer Ben.
>
> > Perhaps V8 could be made smart enough to distinguish between benign
> > and non-benign prototype tampering but the subset that can be proven
> > safe is probably so small that it's not worth the complexity and
> > overhead.
>
> Yes, I agree.
> Alternatively, could v8 use the pre 7.1 impl of Array#splice when the 
> prototype has been modified?
> Obviously, this is easier said than done and I'm guessing that it might not 
> be an easy task.
> But it's worth noting that the pre 7.1 impl performance (with and without 
> prototype tampering) were similar.
> Not sure how it was all made possible... but it was great for us :)
>
> Anyway thanks again for your input!
> Have a nice day

Older versions of V8 called out to this JS-with-extensions code:
https://github.com/v8/v8/blob/7.0.1/src/js/array.js#L599-L642 - I
don't speak for the V8 team but I don't believe they're looking to
return to that approach.

If Array.p.splice() performance is vital to you, you can try
open-coding it. I did something similar in Node.js a few years ago, to
great effect: 
https://github.com/nodejs/node/commit/d3f8db124463e478420d8bba6fa5cf13af7b4ecb

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9N8HCcKnnpvBFdnGfHRYRoiWF8pSVgqBgRyOP8_2MZfw%40mail.gmail.com.


Re: [v8-users] Array splice is not optimized when Array.prototype has been altered in v8 7.1+

2020-09-24 Thread Ben Noordhuis
On Wed, Sep 23, 2020 at 11:26 AM Guillaume Grossetie
 wrote:
>
> Hello,
>
> I'm working on the Opal project and I've noticed that Array#splice is not 
> optimized anymore (ie. 4-8 times slower) when using a recent version of v8.
>
> To reproduce this slowdown I'm using the following code:
>
> const arr = []
> for (let j = 0; j < 5; j++) {
>   arr.push('index' + j)
> }
>
> Object.setPrototypeOf(Array.prototype, {})
>
> let r
> for (let i = 0; i < 1000; i++) {
>   r = arr.splice(0, 1)
> }
> console.log(r)
>
> You can run the above code against Node 10, which is using v8 version < 7, 
> and against Node 12, which is using v8 version > 7.8.
> Please note that removing "Object.setPrototypeOf(Array.prototype, {})" will 
> effectively enable the optimization.
>
> I think the reason is that Array#splice is now using a Torque implementation 
> where "fast" splice is only used when Array.prototype is pristine :
>
> https://github.com/v8/v8/blob/4b9b23521e6fd42373ebbcb20ebe03bf445494f9/src/builtins/array-splice.tq#L125
>
> I'm well aware that we should not mess with prototypes[2][3] but is there any 
> workaround to get an optimized version of splice even if prototype has been 
> altered?
> Or do you have any idea on how we could mitigate this issue?
>
>
> Thanks for your help,
> Guillaume
>
> [1] https://github.com/opal/opal
> [2] https://mathiasbynens.be/notes/prototypes
> [3] https://mathiasbynens.be/notes/shapes-ics

I don't think so.

Array.p.splice() returns a new array. array-splice.tq has a fast path
for that (ExtractFastJSArray, defined in
src/codegen/code-stub-assembler.cc) but that's only sound when
Array.prototype is unmodified, hence the
IsPrototypeInitialArrayPrototype() check.

Perhaps V8 could be made smart enough to distinguish between benign
and non-benign prototype tampering but the subset that can be proven
safe is probably so small that it's not worth the complexity and
overhead.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9UGMipbLjEjkJzFGQvu1V-nCmEiOSS5Kta60_-qeubKQ%40mail.gmail.com.


Re: [v8-users] How can I get the resolved promise result?

2020-09-17 Thread Ben Noordhuis
On Thu, Sep 17, 2020 at 12:13 AM Yao Xiao  wrote:
>
> Thanks for the pointer Ben. I encountered another issue while following your 
> suggestion:
>
> For evaluating the script "new Promise(() => {})", I'd expect 
> result->IsPromise() is true. However, in some cases I'm seeing 
> result->IsPromise() is false if some code are executed before.
>
> I don't have a small example as I couldn't pinpoint the issue. But I'll see 
> this issue if I execute the tensorflow.js source code (from 
> https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.4.0/dist/tf.js) before the 
> promise, in which case I'll see result->IsPromise() is false. However, when I 
> print the status from v8::String::Utf8Value(isolate, 
> result->ToDetailString(context).ToLocalChecked()), it still outputs 
> "#". So I'm confused.
>
> It seems that the execution of tensorflow.js is interfering with something, 
> but I'm not sure how to debug. FYI, I *think* the execution of tensorflow.js 
> succeeded, because I saw no compile/run error, and after that I could still 
> compile/run some tensorflow functions, or just compile/run some other toy 
> functions. It's just that a promise is no longer evaluated to be a promise.
>
> Any ideas why this happens?

The file you link to seems to have its own custom Promise
implementation, something that the spec allows (search for
'thenables'.)

You can't really detect that except by checking if it's a thenable (an
object with a .then method) and hope for the best.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc90VC8tkwk0_hpgQQ9H2qumXh8YefmVe0siVW_N-1RNzQ%40mail.gmail.com.


Re: [v8-users] How can I get the resolved promise result?

2020-09-16 Thread Ben Noordhuis
On Wed, Sep 16, 2020 at 8:56 AM Yao Xiao  wrote:
>
> Hi v8-users,
>
> I'm new to v8.
>
> For a "script" that has a call to a sync function that returns an integer, I 
> figured I could do the following to get the result in C++:
>
> v8::Local result = script->Run(context).ToLocalChecked();
> int result_int = result->Int32Value(context).FromJust();
>
> I'm wondering if there's a way to get (i.e. make C++ aware of) the return 
> value an async function? I tried to use await but it seems that the script 
> won't compile.

You can attach your own .then and .catch callbacks if the script's
return value is a promise (which is what the return value of an async
function really is):

  if (result->IsPromise()) {
Local promise = result.As();
if (promise->State() == Promise::kPending) {
  Local resolve = Function::New(context,
Resolve).ToLocalChecked();
  Local reject = Function::New(context, Reject).ToLocalChecked();
  promise = promise.Then(resolve, reject).ToLocalChecked();
  } else {
result = promise->Result();  // note: distinguish between
kFulfilled and kRejected
// ...
  }

You'll need to pump the event loop and/or the microtask queue in order
for the promise to resolve.

Apropos the await keyword, that isn't accepted at the top-level scope
(outside an async function) unless you're executing the script as an
ES module and the --harmony_top_level_await flag is set.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-SadnFfU7oaG%2BMMnrZ_teaffm7toFjOC1372e%2BMmqXZA%40mail.gmail.com.


Re: [v8-users] Cleaning up after a Posix fork

2020-09-14 Thread Ben Noordhuis
On Mon, Sep 14, 2020 at 1:46 AM Sam Saffron  wrote:
>
>
> It is clear that there is no support for OS level forking in v8, this has 
> been mentioned previously.
>
> However what is unclear is how to perform rudimentary cleanups so isolates 
> and contexts can continue to be used post forking.
>
> In MiniRacer (v8 binding for Ruby) I have a trivial repro of a hang:
>
> https://github.com/rubyjs/mini_racer/issues/175
>
> ```
> (gdb) bt
> #0  0x7f18d4fb202d in pthread_cond_signal@@GLIBC_2.3.2 () from 
> /usr/lib/libpthread.so.0
> #1  0x7f18d084a5fc in 
> v8::platform::DelayedTaskQueue::Append(std::unique_ptr std::default_delete >) ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #2  0x7f18d0849db0 in 
> v8::platform::DefaultWorkerThreadsTaskRunner::PostTask(std::unique_ptr  std::default_delete >) () from 
> /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #3  0x7f18d0848f51 in 
> v8::platform::DefaultPlatform::CallOnWorkerThread(std::unique_ptr std::default_delete >) () from 
> /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #4  0x7f18d1014653 in v8::internal::ConcurrentMarking::ScheduleTasks() ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #5  0x7f18d09732ab in 
> v8::internal::MarkCompactCollector::MarkLiveObjects() ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #6  0x7f18d0972bb1 in 
> v8::internal::MarkCompactCollector::CollectGarbage() ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #7  0x7f18d09468ea in v8::internal::Heap::MarkCompact() () from 
> /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #8  0x7f18d0943389 in 
> v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, 
> v8::GCCallbackFlags) ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #9  0x7f18d0940f10 in 
> v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, 
> v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) () from 
> /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #10 0x7f18d094141e in 
> v8::internal::Heap::CollectAllAvailableGarbage(v8::internal::GarbageCollectionReason)
>  ()
>from /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #11 0x7f18d087cdec in v8::Isolate::LowMemoryNotification() () from 
> /home/sam/Source/mini_racer/lib/mini_racer_extension.so
> #12 0x7f18d08445f6 in rb_isolate_low_memory_notification 
> (self=94876640147440)
> at ../../../../ext/mini_racer_extension/mini_racer_extension.cc:783
> ```
>
> Contexts in mini_racer always get clean isolates, so somehow the task queue 
> appears to be wedged post fork due to some global state maybe?
>
> What rudimentary cleanup can we do post for to ensure that new isolates and 
> contexts can continue to be used?
>
> isolate->Dispose() seems insufficient.
>
> We are using v8 8.4

You'll also have to call V8::Dispose() and V8::ShutdownPlatform(), in
that order, then call V8::InitializePlatform() and V8::Initialize()
again, also in that order. Even then I wouldn't want to bet it
actually works, or keeps working going forward.

You can go a step further and add a dlclose+dlopen libv8.so in between
to force even more cleanup, but again, that's still no guarantee it'll
work. A better bet is to prefork before initializing V8.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_mRKJCXVsP5EQGBioyzyokxPKKf%2BvDYXh0GRdVPS8v0Q%40mail.gmail.com.


Re: [v8-users] Why is my javascript source code kept in the heap during runtime?

2020-09-06 Thread Ben Noordhuis
On Sat, Sep 5, 2020 at 11:10 PM Doron Roberts-Kedes  wrote:
>
> Hello V8 community,
>
> In a heap snapshot of my production node server I noticed that every 
> "compiled code" entry has a "source" field containing a string of what 
> appears to be the original javascript source code. I have a few questions 
> about this:
>
> Are these strings required at runtime for JIT compilation? This source I've 
> found says that: "bytecode is used as the source of truth, removing the need 
> to re-parse Javascript during compilation. This means that with bytecode, 
> TurboFan’s deoptimization no longer requires the original source code." I'm 
> taking this to mean these strings are not needed at runtime for JIT 
> compilation. Am I interpreting this correctly?
> If these strings are not needed for JIT compilation at runtime, are they 
> maintained at runtime in order to make the program more easily debug-able?
> If they are included for debugging purposes and not strictly necessary, is 
> there any way to disable this?
>
>
> Thanks!
>
> Best,
> Doron

I'm 98% sure it's primarily because of Function.prototype.toString()
and that there's no way to disable that, secondarily for debugging.

There's an internal mechanism to mark JS functions as native that lets
V8 throw away the source code but it's not available to regular JS. I
don't think it's even exposed through the public C++ API.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-jKmtQQhN563eUBzsEUK94gU2zf3QX%2BdLoYi4iMbO%3D_Q%40mail.gmail.com.


Re: [v8-users] std::atomic in v8.h

2020-08-31 Thread Ben Noordhuis
On Mon, Aug 31, 2020 at 4:12 PM Alex Kodat  wrote:
>
> In doing a clang build under Windows (for reasons I'll get into in another 
> post) I hit a the following issue:
>
> [4/1336] CXX obj/src/inspector/inspector/v8-stack-trace-impl.obj
> FAILED: obj/src/inspector/inspector/v8-stack-trace-impl.obj
> ..\..\third_party\llvm-build\Release+Asserts\bin\clang-cl.exe /nologo 
> /showIncludes:user "-imsvc..\..\..\..\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.25.28610\ATLMFC\include" 
> "-imsvc..\..\..\..\Program Files (x86)\Microsoft Visual 
> Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include" 
> "-imsvc..\..\..\..\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" 
> "-imsvc..\..\..\..\Program Files (x86)\Windows 
> Kits\10\include\10.0.19041.0\ucrt" "-imsvc..\..\..\..\Program Files 
> (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-imsvc..\..\..\..\Program 
> Files (x86)\Windows Kits\10\include\10.0.19041.0\um" 
> "-imsvc..\..\..\..\Program Files (x86)\Windows 
> Kits\10\include\10.0.19041.0\winrt" "-imsvc..\..\..\..\Program Files 
> (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" -DUSE_AURA=1 
> "-DCR_CLANG_REVISION=\"llvmorg-12-init-3492-ga1caa302-1\"" -D_HAS_NODISCARD 
> -D_HAS_EXCEPTIONS=0 -D__STD_C -D_CRT_RAND_S -D_CRT_SECURE_NO_DEPRECATE 
> -D_SCL_SECURE_NO_DEPRECATE -D_ATL_NO_OPENGL -D_WINDOWS 
> -DCERT_CHAIN_PARA_HAS_EXTRA_FIELDS -DPSAPI_VERSION=2 -DWIN32 -D_SECURE_ATL 
> -DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP -DWIN32_LEAN_AND_MEAN -DNOMINMAX 
> -D_UNICODE -DUNICODE -DNTDDI_VERSION=NTDDI_WIN10_VB -D_WIN32_WINNT=0x0A00 
> -DWINVER=0x0A00 -DNDEBUG -DNVALGRIND -DDYNAMIC_ANNOTATIONS_ENABLED=0 
> -DV8_TYPED_ARRAY_MAX_SIZE_IN_HEAP=64 -DENABLE_MINOR_MC -DV8_INTL_SUPPORT 
> -DENABLE_HANDLE_ZAPPING -DV8_CONCURRENT_MARKING 
> -DV8_ENABLE_LAZY_SOURCE_POSITIONS -DV8_SHARED_RO_HEAP 
> -DV8_WIN64_UNWINDING_INFO -DV8_ENABLE_REGEXP_INTERPRETER_THREADED_DISPATCH 
> -DV8_SNAPSHOT_COMPRESSION -DV8_DEPRECATION_WARNINGS 
> -DV8_IMMINENT_DEPRECATION_WARNINGS -DV8_TARGET_ARCH_X64 -DV8_HAVE_TARGET_OS 
> -DV8_TARGET_OS_WIN -DDISABLE_UNTRUSTED_CODE_MITIGATIONS 
> -DV8_DEPRECATION_WARNINGS -DV8_IMMINENT_DEPRECATION_WARNINGS 
> -DV8_DEPRECATION_WARNINGS -DV8_IMMINENT_DEPRECATION_WARNINGS -I../.. -Igen 
> -I../../include -I../.. -I../../include -Igen -fcolor-diagnostics 
> -fmerge-all-constants -fcrash-diagnostics-dir=../../tools/clang/crashreports 
> -mllvm -instcombine-lower-dbg-declare=0 -fcomplete-member-pointers /Gy /FS 
> /bigobj /utf-8 /Zc:twoPhase /Zc:sizedDealloc- /X 
> /D__WRL_ENABLE_FUNCTION_STATICS__ -fmsc-version=1916 /guard:cf,nochecks -m64 
> /Brepro -Wno-builtin-macro-redefined -D__DATE__= -D__TIME__= -D__TIMESTAMP__= 
> -Xclang -fdebug-compilation-dir -Xclang . -no-canonical-prefixes /W4 
> -Wimplicit-fallthrough -Wunreachable-code -Wthread-safety -Wextra-semi 
> /wd4091 /wd4127 /wd4251 /wd4275 /wd4312 /wd4324 /wd4351 /wd4355 /wd4503 
> /wd4589 /wd4611 /wd4100 /wd4121 /wd4244 /wd4505 /wd4510 /wd4512 /wd4610 
> /wd4838 /wd4995 /wd4996 /wd4456 /wd4457 /wd4458 /wd4459 /wd4200 /wd4201 
> /wd4204 /wd4221 /wd4245 /wd4267 /wd4305 /wd4389 /wd4702 /wd4701 /wd4703 
> /wd4661 /wd4706 /wd4715 -Wno-missing-field-initializers -Wno-unused-parameter 
> -Wno-c++11-narrowing -Wno-unneeded-internal-declaration 
> -Wno-undefined-var-template -Wno-nonportable-include-path -Wno-psabi 
> -Wno-ignored-pragma-optimize -Wno-implicit-int-float-conversion 
> -Wno-final-dtor-non-final-class -Wno-builtin-assume-aligned-alignment 
> -Wno-deprecated-copy -Wno-non-c-typedef-for-linkage -Wno-string-concatenation 
> -Wmax-tokens /Z7 -gcodeview-ghash -Xclang -debug-info-kind=constructor /MT 
> -Wheader-hygiene -Wstring-conversion -Wtautological-overlap-compare 
> -Wmissing-field-initializers -Wunreachable-code -Wshorten-64-to-32 /wd4245 
> /wd4267 /wd4324 /wd4701 /wd4702 /wd4703 /wd4709 /wd4714 /wd4715 /wd4718 
> /wd4723 /wd4724 /wd4800 /O2 /Ob2 /Oy- /Zc:inline /Gw -Wexit-time-destructors 
> -Wno-trigraphs /TP /wd4577 /GR- /c ../../src/inspector/v8-stack-trace-impl.cc 
> /Foobj/src/inspector/inspector/v8-stack-trace-impl.obj 
> /Fd"obj/src/inspector/inspector_cc.pdb"
> In file included from ../../src/inspector/v8-stack-trace-impl.cc:5:
> In file included from ../..\src/inspector/v8-stack-trace-impl.h:11:
> In file included from ../..\include/v8-inspector.h:14:
> ../../include/v8.h(912,27): error: no template named 'atomic' in namespace 
> 'std'
> reinterpret_cast*>(_)->store(new_val,
>  ~^
> ../../include/v8.h(920,34): error: no template named 'atomic' in namespace 
> 'std'
> return reinterpret_cast const*>(_)->load(
> ~^
> 2 errors generated.
>
> Weirdly, I don't get similar errors with clang under say MacOS and I'm not 
> sure I see why clang is seeing fit to expand the TracedReferenceBase template 
> (MSVC doesn't seem to) but, all that said, it seems a little tacky having a 
> std::atomic reference in v8.h without a 

Re: [v8-users] Is it possible to implement N:M schedule model using isolate and native thread?

2020-08-12 Thread Ben Noordhuis
On Wed, Aug 12, 2020 at 5:08 AM Ran Aizen  wrote:
>
> Thank you Ben~
>
> I just read the a little code implementation, but I still confused
> when should I use isolate->enter() and isolate->exit() ?
> What's the use case of them?

You use them for switching between isolates (at points where it's safe
to do so, of course.)

Rather than juggling enters and exits manually, I recommend using
v8::Isolate::Scope.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8ZfvSq6EMnNcgory6fWzDMvf3KGXbtTyoz9PD8mQmhEA%40mail.gmail.com.


Re: [v8-users] Is it possible to implement N:M schedule model using isolate and native thread?

2020-08-11 Thread Ben Noordhuis
On Tue, Aug 11, 2020 at 5:56 PM Ran Aizen  wrote:
> From your answer, I guess that v8 no longer maintaining the execution context 
> after "isolate->TerminateExecution" and cleanup the stack frame, so we can't 
> continue the execution from where we stopped?

That's right. Think of it like this: your C++ code calls into the VM
and the VM can call out to your code. It's not safe to call
isolate->Exit() as long as there are VM stack frames on the call
stack.

isolate->TerminateExecution() works because it unwinds the VM stack
and returns control to your C++ code.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9krE_Bx%2BJsRcN6cTi_YRwkoZ5eW8YeiXHwdRjJRFc5_A%40mail.gmail.com.


Re: [v8-users] Is it possible to implement N:M schedule model using isolate and native thread?

2020-08-11 Thread Ben Noordhuis
On Tue, Aug 11, 2020 at 9:38 AM Ran Aizen  wrote:
>
> I saw the v8 description says:
>
> > Isolate represents an isolated instance of the V8 engine. V8 isolates have 
> > completely separate states. Objects from one isolate must not be used in 
> > other isolates. The embedder can create multiple isolates and use them in 
> > parallel in multiple threads. An isolate can be entered by at most one 
> > thread at any given time. The Locker/Unlocker API must be used to 
> > synchronize.
>
> According to my understanding, it seems one isolate can be run in multiple 
> thread (not in same time), and multiple isolate can be managed in one thread.
>
> Because I want to use Isolate as the VM for my program in multi-tenant case, 
> so I read some of the v8 API, I found that `v8::Isolate` has some APIs like:
>
> - `Isolate::enter`, `Isolate::exit`
> - `Isolate::TerminateExecution`
> - `Isolate::CancelTerminateExecution`
> - `Isolate::RequestInterrupt`
>
> So, is it possible to "schedule" massive isolates among multiple threads 
> using v8 public APIs like above or does v8 support to achieve the "schedule" ?
>
> The "schedule" here means maybe:
>
> 1. work stealing: let a thread run an isolate which was created and init by 
> other thread to balanced the isolate distribution.
> 2. round-robin: one thread created multiple isolate, when an special event  
> happend (maybe recv an os signal), one of the running isolate could be paused 
> the execution progress, save the execution context and switch into other 
> isolate, after other isolate finished, resume the previous isolate's 
> execution.

I believe your question is whether V8 supports preemptive
rescheduling, i.e., without cooperation from the executing script?

It doesn't. It's allowed to call isolate->RequestInterrupt() and then
call isolate->TerminateExecution() from the callback but not
isolate->Exit().

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-Wa-6XKARB%2BWMRm6cq5QfsevkzXpCiRos7OUtQU6hjZg%40mail.gmail.com.


Re: [v8-users] Serialization Side Effects

2020-08-04 Thread Ben Noordhuis
On Tue, Aug 4, 2020 at 10:32 PM Adrienne Walker  wrote:
>
> On Thu, Jul 30, 2020 at 9:57 PM Ben Noordhuis  wrote:
>>
>> On Thu, Jul 30, 2020 at 8:21 PM Adrienne Walker  wrote:
>> > Is there any way to know from a v8::Value whether serializing it will have 
>> > side effects (at all or on particular properties)?
>>
>> Apart from checking whether it's primitive (v->IsNullOrUndefined() ||
>> v->IsBoolean() || ...), I believe the answer is 'no' . Non-primitive
>> values can have getters and getters execute arbitrary code.
>>
>> Checking for only simple properties recursively is an option but
>> probably not faster and you'll need to handle cycles and a ton of edge
>> cases (what if the property is a pending promise? what if it's a
>> WeakMap? etc.)
>
>
> Can I use HasRealNamedProperty/GetRealNamedProperty to see if I can access 
> those properties without side effects and then check if those values are 
> primitive from there? I suspect that most indexeddb keys being provided here 
> are primitive string values inside a single simple object, and so am I trying 
> to figure out how to fast path this case.

Yes, that could work, but you'll have to recurse into non-primitive
property values. GetRealNamedProperty() and co are fairly slow
(although probably not much slower than Get() - the whole C++ API is
fairly slow compared to native JS property access) so you'll probably
have to benchmark whether it's an improvement over the naive approach.

> Is there a way to tell if a property is one of these complicated edge cases 
> that you mention?

Exhaustive v->IsPromise() || v->IsWeakMap() || ... checks. :-)

>> The debugger has a "side-effect-free evaluate" mode but that operates
>> on functions, not values. You could use it to check getters for side
>> effects (and promises, and...) but the algorithm is conservative (can
>> report side effects when there are none) and runs in O(n) time
>> relative to the function's bytecode size.
>
>
> Given the potential performance issues there, this doesn't sound like a 
> plausible approach.
>
> The only other thing we thought of was if there was some way to have some 
> sort of observer as a part of serialization that could record the values 
> without having to deserialize again to access.  I worry that this might be 
> too invasive to v8's serialization though.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8t2V3UykM5EBNrmZHApEYoDmzdiLKcdz-gbvoLuya1tQ%40mail.gmail.com.


Re: [v8-users] Serialization Side Effects

2020-07-30 Thread Ben Noordhuis
On Thu, Jul 30, 2020 at 8:21 PM Adrienne Walker  wrote:
> Is there any way to know from a v8::Value whether serializing it will have 
> side effects (at all or on particular properties)?

Apart from checking whether it's primitive (v->IsNullOrUndefined() ||
v->IsBoolean() || ...), I believe the answer is 'no' . Non-primitive
values can have getters and getters execute arbitrary code.

Checking for only simple properties recursively is an option but
probably not faster and you'll need to handle cycles and a ton of edge
cases (what if the property is a pending promise? what if it's a
WeakMap? etc.)

The debugger has a "side-effect-free evaluate" mode but that operates
on functions, not values. You could use it to check getters for side
effects (and promises, and...) but the algorithm is conservative (can
report side effects when there are none) and runs in O(n) time
relative to the function's bytecode size.

(It's actually worse than that. It does bytecode analysis + runtime
evaluation in a throwaway context. I suspect it hangs on a busy loop.
That makes it... O(Infinity)?)

The relevant methods are DebugEvaluate::Global() and
Debug::PerformSideEffectCheck(). Neither are currently exposed by the
public API except indirectly, through the Debugger.evaluate and
Debugger.evaluateOnCallFrame inspector protocol commands.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_0bLqJu4SddP%2BOaC9gnJPN322gcc2ZLvBA0BwkwJ1XEw%40mail.gmail.com.


Re: [v8-users] Evaluate ES6-Module with undefined function

2020-07-29 Thread Ben Noordhuis
On Wed, Jul 29, 2020 at 10:24 AM Hans Maier  wrote:
>
> Hi,
>
> im upgrading from 8.0.426.26 to 8.4.371.22.
>
> I've a small test case where I evalute (using v8::Module::Evaluate) a 
> ES6-Module with the following content:
> 
> hello();
> 
>
> In 8.0.x I get an exception:
> HelloWorld1.js:1: 
> hello();
> ^
> ReferenceError: hello is not defined
> at HelloWorld1.js:1:1
>
> In 8.4.x there is no exception (it succeddes).
>
> It this expected?
>
> Thanks.

It depends. What does module->GetStatus() return before and after and
what does module->Evaluate() itself return? Do you set the
--harmony_top_level_await flag?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_y2jimnVvBzJpDG%3DjGG851qWP9j84ND_bTcu_gYBEwxw%40mail.gmail.com.


Re: [v8-users] (v8 8.4) libv8_libplatform.a: error adding symbols: Malformed archive

2020-07-21 Thread Ben Noordhuis
On Mon, Jul 20, 2020 at 2:08 PM Richard Hughes
 wrote:
>
> I have built and linked against `v8` 8.4 successfully on Windows and Mac, but 
> with Ubuntu 18.04, I get the following error when I try to link against 
> `libv8_libplatform.a` that was built:
>
> ../../lib/Linux/libv8_libplatform.a: error adding symbols: Malformed 
> archive
> clang: error: linker command failed with exit code 1 (use -v to see 
> invocation)
> CMakeFiles/v8_test_project.dir/build.make:86: recipe for target 
> 'v8_test_project' failed
> make[2]: *** [v8_test_project] Error 1
>
> Here are the `gn` arguments I used:
>
> is_component_build = false
> is_debug = false
> target_cpu = x64
> use_custom_libcxx = false
> v8_monolithic = true
> v8_use_external_startup_data = false
> is_clang = true
> use_lld = true
> use_sysroot = false
> linux_use_bundled_binutils = true
>
> The `v8` documentation doesn't seem to indicate that I need to do anything 
> particular to setup the build chain for Ubuntu, but I may have missed 
> something.
>
> Here is my `clang` version:
>
> Ubuntu clang version 
> 10.0.1-++20200708123507+ef32c611aa2-1~exp1~20200707224105.191
> Target: x86_64-pc-linux-gnu
> Thread model: posix
> InstalledDir: /usr/bin
> Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
> Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/7
> Found candidate GCC installation: 
> /usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0
> Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/8
> Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
> Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7
> Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7.5.0
> Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/8
> Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
> Candidate multilib: .;@m64
> Selected multilib: .;@m64

I bumped into that error when I ran out of disk space. Maybe that's
what's happening here?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_Yqt22tZQpHQkXMfqpmqkJd4vtLTabdiK%3Dq1MBFHx3MQ%40mail.gmail.com.


Re: [v8-users] Debugging ES6 modules with V8 inspector

2020-06-26 Thread Ben Noordhuis
On Thu, Jun 25, 2020 at 2:35 AM Nupoor Kotasthane  wrote:
>
> I also notice that the 'this' object in the Debugger.CallFrame objects have 
> their 'type' set to 'undefined' when debugging ES6 modules. I also notice 
> that the variables declared in the starting module are missing from the scope 
> when I try to inspect the scope object with Runtime.getProperties.  Is this 
> expected behavior?
>
>
>
> On Tuesday, June 23, 2020 at 2:56:57 PM UTC-7, Nupoor Kotasthane wrote:
>>
>> Hi Ben,
>>
>> We have embedded V8 version 6.7 in our product. We use it to run and debug 
>> JavaScript. While debugging scripts is working okay, debugging ES6 modules 
>> using the inspector has this one problem. When using 
>> Debugger.evaluateOnCallFrame to inspect variables we keep getting an 
>> inspector response with reference errors saying the variables are not 
>> defined. This is true for all locally declared variables within the current 
>> scope in the "mjs" module (I do not see this problem with the imported 
>> module, only the importing module).
>>
>> It seems like symbols are not generated for the importing 'mjs' module. So 
>> do we have to do anything special for modules for this to work? I can share 
>> my example if and inspector responses if that will help.
>>
>> Thanks,
>> Nupoor

It's possible I'm misunderstanding you but it sounds like it's working
as expected.

ES modules run in strict mode. Function calls (not method calls) have
`this` set to `undefined`, and top-level variables are local to the
module, not global.

If that's not what you mean, can you share some example code and
expected vs. actual output?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8RiJDLyAeuteKuYmzpxNUQXwJSoSKmhE0dyrCSB1d%3DBA%40mail.gmail.com.


Re: [v8-users] Debugging ES6 modules with V8 inspector

2020-06-23 Thread Ben Noordhuis
On Mon, Jun 22, 2020 at 8:18 PM Nupoor Kotasthane  wrote:
>
> Hi all,
>
> Is the V8 inspector equipped to debug ES6 modules? Our product embeds V8 and 
> and we integrate with the V8 inspector and use it to debug JavaScript. We 
> have noticed issues when we try to debug ES6 modules with the inspector.
>
> Thanks,
> Nupoor

We haven't noticed any major issues in Node.js when it comes to
debugging ES modules. Can you go into details?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc91mdOcu6VFUan18oKrtkjD7kTYUcNLPXJc%2BP24cruh9w%40mail.gmail.com.


Re: [v8-users] Weak Persistent callback and threading

2020-06-12 Thread Ben Noordhuis
On Thu, Jun 11, 2020 at 6:52 PM Jonathan Resnick  wrote:
>
> I set up a weak callback like so:
>
> UniquePersistent target(isolate, obj);
> target.SetWeak(args, MyCallback, v8::WeakCallbackType::kParameter);
>
> In my testing so far, it appears that MyCallback runs on the same thread as 
> the JS code is executing on. Is it safe to assume that this callback *always* 
> runs on the JS execution thread? I need to free some memory in this callback, 
> and obviously my code can be significantly simpler if I don't need to worry 
> about synchronizing access to my data-structures.

Yes, it runs on the same thread.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-2_fQZmKNkQZBi28uenxaAbf6K5kQ8XdyeHN4JQcXkvQ%40mail.gmail.com.


Re: [v8-users] How to check the "undefined" or "null" object result

2020-06-09 Thread Ben Noordhuis
On Mon, Jun 8, 2020 at 11:56 AM Elmi Ahmadov  wrote:
>
> What do you mean it needs to be same? I don't set it explicitly to any value 
> in my gn args file and it's "true" by default
>
> v8_enable_31bit_smis_on_64bit_arch
> Current value (from the default) = true
> From //BUILD.gn:110

That's what I mean. If you turn on v8_enable_31bit_smis_on_64bit_arch,
you also need to build your downstream project with
-DV8_31BIT_SMIS_ON_64BIT_ARCH.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9mFm6DsbNcp4YnsuQsy1G%2BGaq9XTnPChYtOe%3DUdYMn_w%40mail.gmail.com.


Re: [v8-users] How to check the "undefined" or "null" object result

2020-06-08 Thread Ben Noordhuis
On Sat, Jun 6, 2020 at 12:05 AM Elmi Ahmadov  wrote:
>
> Previously, I was using the V8 version 7.4.x and I have check method to test 
> if the result object from the script execution is undefined/null or real 
> object. Which works fine with the older version of the V8.
>
> But now, I'm using V8 version 8.1.307 and my check does not work anymore.
>
> This is the code snippet to reproduce the issue:
> // create Isolate*, v8::Local> and ...
> v8::Handle undefinedResult = v8::Undefined(isolate);
> v8::Handle nullResult = v8::Null(isolate);
>
> std::cout << "isUndefined: " << undefinedResult->IsUndefined() << std::endl;
> std::cout << "isNull: " << nullResult->IsNull() << std::endl;
>
> with the V8 version 7.4.x, the snippet produces the following output:
> isUndefined: 1
> isNull: 1
>
> But things turn out different for the V8 version 8.1.307, the same snippet 
> produces a different output:
> isUndefined: 0
> isNull: 0
>
> This is my gn args to generate the monolithic V8 7.4.x library:
> target_os = "linux"
> target_cpu = "x64"
> is_component_build = false
> is_debug = false
> use_custom_libcxx = false
> v8_monolithic = true
> v8_use_external_startup_data = false
> symbol_level = 0
> v8_enable_i18n_support= false
>
> I used the same gn args to generate the V8 version 8.1.307, but then V8 
> immediatelly crashes when `->IsUndefined()`called. I found that V8 8.1 
> contains a pointer compression feature so I disabled to see how this would 
> effect the result, now there is no crash but wrong result.
> target_os = "linux"
> target_cpu = "x64"
> is_component_build = false
> is_debug = false
> use_custom_libcxx = false
> v8_monolithic = true
> v8_use_external_startup_data = false
> symbol_level = 0
> v8_enable_i18n_support= false
> v8_enable_pointer_compression = false
>
> What is the actual cause of this issue? How can I fix it? Maybe I'm missing 
> something but I don't know what it is.

v8_enable_31bit_smis_on_64bit_arch (corresponds to
-DV8_31BIT_SMIS_ON_64BIT_ARCH) also needs to be the same when building
V8 and your project.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9hxGLbfq%3DBXALCLZS7DetFDedx5pQS2KU8BEFSUHkdPw%40mail.gmail.com.


Re: [v8-users] V8 build fails on //third_party/zlib dependency

2020-05-23 Thread Ben Noordhuis
On Thu, May 21, 2020 at 6:12 PM Dirk Becker  wrote:
>
> Hi,
>
> my OSX build of V8 failed with an error
> ERROR at //BUILD.gn:3584:5: Unable to load 
> "/Volumes/Disk2/v8/third_party/zlib/BUILD.gn".
> correctly so, as there is no zlib in v8/third_party .
>
> I commented out the matching dependency lines, introduced in 
> https://chromium.googlesource.com/v8/v8.git/+/858e3c7ef7bc80ea1767737853971e4e6a4633af
> Along the suggestion there, I also added v8_disable_snapshot_compression = 
> true to my args.gn
>
>
> After the warning
> > Did you mean "v8_enable_snapshot_compression"?
> I then used an v8_enable_snapshot_compression = false
>
>
> Next is a compile error:
>
> [939/1601] CXX obj/v8_base_without_compiler/snapshot-compression.o
> FAILED: obj/v8_base_without_compiler/snapshot-compression.o
> ../../src/snapshot/snapshot-compression.cc:10:10: fatal error: 
> 'third_party/zlib/google/compression_utils_portable.h' file not found
>
>
> v8_enable_snapshot_compression takes me to a define V8_SNAPSHOT_COMPRESSION
> Next attempt: add several #ifdef V8_SNAPSHOT_COMPRESSION in 
> snapshot-compression.cc, snapshot-utils.cc and so forth.
> A dead end, more and more dependencies - snapshot compression is to stay, IMO 
> that argument / option is toast.
>
>
> Therefor maybe it is easier to add "third_party/zlib" .
> Next problem though: Considering that reference to … 
> "google/compression_utils_portable.h" this is likely to be a special build.
>
>
> As I am pretty new to V8, how should I continue?
>
> Thanks,
> Dirk

It sounds like you did a regular `git clone`? See the instruction at
[0], you need to use the fetch command from depot_tools. That will
also check out dependencies, among other things.

I maintain a fork[1] of V8 that uses cmake as the build tool. It lets
you use the regular cmake workflow but it doesn't support every option
that GN supports (yet - pull requests welcome.)

[0] https://v8.dev/docs/source-code
[1] https://github.com/bnoordhuis/v8-cmake

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8m9pG5ek6RQXVTAo9dKo9z4wRmDdro%2BZuDBfvrknJcfw%40mail.gmail.com.


Re: [v8-users] how to use mksnapshot to make a warm-up snapshot?

2020-04-26 Thread Ben Noordhuis
On Sun, Apr 26, 2020 at 1:10 PM Chris Chen  wrote:
>
> Umm, I used d8 to run this js file, it worked fine. In this case , how to 
> find out where throws this exception?

The short answer is "you don't", at least not easily. :-)

mksnapshot won't print JS error messages or stack traces. The one
thing I can tell you is that it's _probably_ not a runtime exception
but a parse error., otherwise the assert would have been different.
The snapshot scripts should be plain JS scripts, not ES modules.

Oh, and keep in mind that d8 runs your script in a JS environment with
a lot of extras. mksnapshot is just a bare bones execution context.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8KegdFk0rAu1SjFfLgQONQNnOzZVP_c%2Bc3pXYfmS1_PA%40mail.gmail.com.


Re: [v8-users] how to use mksnapshot to make a warm-up snapshot?

2020-04-26 Thread Ben Noordhuis
On Sun, Apr 26, 2020 at 12:41 PM Chris Chen  wrote:
>
> I've tried the command like this:
> ./mksnapshot native.js native.js --startup_blob=native.js.bin 
> --turbo_instruction_scheduling
> but failed:
>>
>> Loading script for embedding: native.js
>> Loading script for warm up: native.js
>>
>> #
>> # Fatal error in , line 0
>> # Check failed: blob.data.
>> #
>> #
>> #
>> #FailureMessage Object: 0x7fff215367a0
>>  C stack trace ===
>> 
>> /home/c/v8/depot_tools/v8-code/v8-8.0.426.26/v8/out.gn/test-8/clang_x64_v8_arm64/libv8_libbase.cr.so(v8::base::debug::StackTrace::StackTrace()+0x13)
>>  [0x7f2f32f60123]
>> 
>> /home/c/v8/depot_tools/v8-code/v8-8.0.426.26/v8/out.gn/test-8/clang_x64_v8_arm64/libv8_libplatform.cr.so(+0xd07d)
>>  [0x7f2f32f3807d]
>> 
>> /home/c/v8/depot_tools/v8-code/v8-8.0.426.26/v8/out.gn/test-8/clang_x64_v8_arm64/libv8_libbase.cr.so(V8_Fatal(char
>>  const*, ...)+0x150) [0x7f2f32f5a2e0]
>> ./mksnapshot(+0x3fecbd) [0x55ebe4d9bcbd]
>> /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f2f31c0f830]
>> ./mksnapshot(_start+0x2a) [0x55ebe4d993ba]
>> Illegal instruction (core dumped)

That probably means you have something in your warm-up script that
throws an exception. The snapshot runtime environment is not forgiving
of programming errors.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_vdpVOowaZPK_5ymPnpq28usTTO3rhv%3DjrBHKFqzkQ3w%40mail.gmail.com.


Re: [v8-users] how to use mksnapshot to make a warm-up snapshot?

2020-04-26 Thread Ben Noordhuis
On Sun, Apr 26, 2020 at 9:15 AM Chris Chen  wrote:
>
> Hi, all,
>
> When using "./clang_x64_v8_arm64/mksnapshot $JS_FILE --startup_blob=$BIN_FILE 
> --turbo_instruction_scheduling",  seemed it only do "Loading script for 
> embedding: xxx", but not include "Loading script for warm up: xxx ".
>
> Is there a  way to generate a warm-up snapshot using mksnapshot?

Yes, just pass an additional filename. The first one is used for
embedding, the second one for warm-up.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_tdvQkTpttmpmAZkq_0Xao2N6M92HF0hv%3D6yTSBbQvEA%40mail.gmail.com.


Re: [v8-users] v8 embedded: crash at Isolate::New when trying to initialize again

2020-04-10 Thread Ben Noordhuis
On Fri, Apr 10, 2020 at 12:47 PM Chris Chen  wrote:
>
> Hi, all, I am embedding v8 into a c++ program, and when trying to initialize 
> an Isolate again, the program crashes.
>
> The way I was doing is made an v8::Isolate as a member field of an JsEngine 
> instance,  then call ~JsEngine() and renew a JsEngine instance. In 
> ~JsEngine(), I do stuff like disposed Isolate, shutdown platform, etc.
>
> This can be reproduced by some modification to samples/hello-world.cc as 
> following:
>
>>> int main(int argc, char* argv[]) {
>>>
>>>   // Initialize V8.
>>>
>>>   v8::V8::InitializeICUDefaultLocation(argv[0]);
>>>
>>>   v8::V8::InitializeExternalStartupData(argv[0]);
>>>
>>>   std::unique_ptr platform = 
>>> v8::platform::NewDefaultPlatform();
>>>
>>>   v8::V8::InitializePlatform(platform.get());
>>>
>>>   v8::V8::Initialize();
>>>
>>>
>>>   // Create a new Isolate and make it the current one.
>>>
>>>   v8::Isolate::CreateParams create_params;
>>>
>>>   create_params.array_buffer_allocator =
>>>
>>>   v8::ArrayBuffer::Allocator::NewDefaultAllocator();
>>>
>>>   v8::Isolate* isolate = v8::Isolate::New(create_params);
>>>
>>>   {
>>>
>>> v8::Isolate::Scope isolate_scope(isolate);
>
>
>// -
>>>
>>>   // ignore. evaluate some js strings here.
>
>   //  --
>>>
>>>   // Dispose the isolate and tear down V8.
>>>
>>>   isolate->Dispose();
>>>
>>>   v8::V8::Dispose();
>>>
>>>   v8::V8::ShutdownPlatform();
>>>
>>>   delete create_params.array_buffer_allocator;
>>>
>>>
>// --
>>>
>>>   // do it again for testing
>
>// --
>>>
>>>   v8::V8::InitializeICUDefaultLocation(argv[0]);
>>>
>>>   v8::V8::InitializeExternalStartupData(argv[0]);
>>>
>>>   std::unique_ptr platform2 = 
>>> v8::platform::NewDefaultPlatform();
>>>
>>>   v8::V8::InitializePlatform(platform2.get());
>>>
>>>   v8::V8::Initialize();
>>>
>>>
>>>   // Create a new Isolate and make it the current one.
>>>
>>>   v8::Isolate::CreateParams create_params2;
>>>
>>>   create_params2.array_buffer_allocator =
>>>
>>>   v8::ArrayBuffer::Allocator::NewDefaultAllocator();
>>>
>>>   v8::Isolate* isolate2 = v8::Isolate::New(create_params2);  // crash here.
>
>
>>>
>>>   return 0;
>>>
>>> }
>
> The output is like this:
>>>
>>> Hello, World!
>>>
>>> 3 + 4 = 7
>>>
>>> Segmentation fault (core dumped)
>>
>>
>
> The backtrace looks like this:
>>
>>
>>
>> #0  __GI___pthread_mutex_lock (mutex=0x128) at 
>> ../nptl/pthread_mutex_lock.c:67
>>
>> #1  0x007f2073 in 
>> v8::internal::wasm::WasmEngine::AddIsolate(v8::internal::Isolate*) ()
>>
>> #2  0x004cadd8 in 
>> v8::internal::Isolate::Init(v8::internal::ReadOnlyDeserializer*, 
>> v8::internal::StartupDeserializer*) ()
>>
>> #3  0x004cb2b9 in 
>> v8::internal::Isolate::InitWithSnapshot(v8::internal::ReadOnlyDeserializer*, 
>> v8::internal::StartupDeserializer*) ()
>>
>> #4  0x007d4735 in 
>> v8::internal::Snapshot::Initialize(v8::internal::Isolate*) ()
>>
>> #5  0x0044abf2 in v8::Isolate::Initialize(v8::Isolate*, 
>> v8::Isolate::CreateParams const&) ()
>>
>> #6  0x0044ad42 in v8::Isolate::New(v8::Isolate::CreateParams const&) 
>> ()
>>
>> #7  0x00414a4e in main ()
>>
>> (gdb) q
>
>
>
> Why this behavior will crash, and how to avoid this?
>
> Any hints would be great, Thanks in advance!

Call V8::InitializePlatform(), V8::Initialize(), V8::Dispose() and
V8::ShutdownPlatform() only once, not twice.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-vt_uXrSH4La%3DcXe-O9qdtGyH7-T%2BSR-u0ymq-s95jOQ%40mail.gmail.com.


Re: [v8-users] Re: Intercepting the setting of static and instance methods

2020-03-03 Thread Ben Noordhuis
On Tue, Mar 3, 2020 at 1:20 PM Darin Dimitrov  wrote:
>
> I tried every possible method but cannot intercept setting members on a 
> Local instance. Also couldn't find any example in the 
> https://chromium.googlesource.com/v8/v8/+/refs/heads/lkgr/test/cctest/test-api-interceptors.cc
>
> Is this simply not possible?

I think for Function objects, you can't do better than SetAccessor(),
but that only lets you intercept a single predetermined named property
and I infer you want to intercept them all.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-i72Cb4aTKcXwtKNT-ZMn9bQNoLsh1Avy-OvprxewzGw%40mail.gmail.com.


Re: [v8-users] Segment fault when update v8..

2020-02-29 Thread Ben Noordhuis
On Sat, Feb 29, 2020 at 5:26 AM YQ Tian  wrote:>
> Thank you for your reply. It is currently found that when I upgrade v8 to 
> 6.8, the dynamic_cast function of my other dynamic library will call the 
> has_unambiguous_public_base function in the v8 library. Normally, the C ++ 
> standard library should be called. This phenomenon is very strange. I Compile 
> the monolith version into multiple libraries according to the previous 
> compilation method. Use the following command
>
> `gn gen out.gn/x64.release --args='is_debug=false target_cpu="x64" 
> v8_static_library=true v8_use_external_startup_data=false'`
>
> `ninja -C out.gn/x64.release`
>
> However, when the v8 library is introduced into the program, a link error 
> occurs. Some symbols like c ++ abi cannot be linked. Will the upgrade you 
> said solve this problem? Or do my compilation commands need to be modified?

V8 links to its own copy of libc++ unless told otherwise. I believe
it's the use_custom_libcxx=false option.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-84RQPSg%2BVb8XcdAmDWydHiriL62YwxECn%2BTDacfzARQ%40mail.gmail.com.


Re: [v8-users] Segment fault when update v8..

2020-02-28 Thread Ben Noordhuis
On Fri, Feb 28, 2020 at 4:05 AM YQ Tian  wrote:
>
> v8 version 6.8.275.32
>
> Hi all!
>
>
> When I upgrade the v8 version, my program crashes. My program statically 
> links the v8 library and also uses another dynamic library. The dynamic 
> library will call the dynamic_cast function,  to see the crash stack of the 
> program. The function enters the has_unambiguous_public_base function through 
> __dynamic_cast Called, right here the program crashes. Upgrading v8, I used 
> the monolith library instead of multiple previous libraries. Through the 
> command `nm` I found that the updated v8 has the symbol __dynamic_cast 
> defined. Can anyone help me understand why monolith has this symbol? What 
> does the monolith version do? Why does my other dynamic library crash?

The monolithic build includes ICU and that uses dynamic_cast in
numerous places. That said, I doubt that's the reason for the crash.

Search the group for recently reported crashes. In most cases it's a
matter of ensuring both V8 and your own code are compiled with
-DV8_COMPRESS_POINTERS.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9AJYppATmLM198dt-Q62GGUSjek1yXeFvTUcZO_n%3DM%3DQ%40mail.gmail.com.


Re: [v8-users] Seg Fault Checking If a Value is a String

2020-02-25 Thread Ben Noordhuis
On Mon, Feb 24, 2020 at 7:35 PM Joel Scarfone  wrote:
>
> V8 Version: 8.0.426.23
>
> Hi all! When updating V8 I found a segmentation fault in tests. I managed to 
> reproduce it with the following code (initialization code stripped, can 
> provide full example upon request):
>
>  Local str = String::NewFromUtf8(isolate, "Hello", 
> v8::NewStringType::kNormal)
> .ToLocalChecked(); Local val = Local::Cast(str); 
> Persistent persistentVal(isolate, val); 
> persistentVal.Get(isolate)->IsString(); // seg fault
>
>
> This worked on previous version. Is this now invalid?

Can you verify that V8 and your code are compiled using the same
compiler flags? More specifically: defines?

A number of people have reported crashes after recent upgrades that
could be traced back to V8 turning on pointer compression but the
downstream projects missing the requisite V8_COMPRESS_POINTERS and
V8_31BIT_SMIS_ON_64BIT_ARCH defines.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8yPh%2BPkRAQQGiVfO3xmP9BAhUqesrhjhTnaNSXCiT8KA%40mail.gmail.com.


Re: [v8-users] API to intercept Promises in V8

2020-02-13 Thread Ben Noordhuis
On Wed, Feb 12, 2020 at 2:31 PM Darin Dimitrov  wrote:
>
> I managed to get this working by replacing the native Promise object by 
> executing the following script:
>
> global.Promise = new Proxy(global.Promise, {
> construct: function(target, args) {
> const origFunc = args[0];
> return new target(function(resolve, reject) {
> origFunc(
> value => executeOnMainThread(resolve.bind(this, value)),
> reason => executeOnMainThread(reject.bind(this, reason))
> );
> });
> }
> });
>
> In this example, I have registered the "executeOnMainThread" function on the 
> global object which will call the specified js function argument on the main 
> thread.
>
> Of course if this can be achieved without replacing the global Promise 
> object, that would be even better.

I don't think V8 lets you do that right now. There's
isolate->SetPromiseHook() but that's intended more for tracing/logging
than for intercepting.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_-5tMKs22kqzFGemO6oqhc584RxaWxMio-xehfciS1bw%40mail.gmail.com.


Re: [v8-users] API to intercept Promises in V8

2020-02-11 Thread Ben Noordhuis
On Tue, Feb 11, 2020 at 8:42 PM Darin Dimitrov  wrote:
>
> I am embedding V8 in my C++ application and I have registered a custom "test" 
> function on the global object taking a callback as parameter:
>
> test(function() {
> console.log("callback");
> });
>
> The "test" function starts a new thread and executes the callback on this 
> thread.
>
> Now I can wrap this function in a Promise:
>
> new Promise(function(resolve, reject) {
> test(resolve);
> }).then(function() {
> console.log("this callback is executed on the background thread created 
> by the 'test' function");
> });
>
> I am looking for a way to somehow hook into V8 promises so that they are 
> always resolved on the main thread of my application.
>
> I thought that using a custom platform might help but couldn't find any 
> useful method that I can override. It does provide the "CallOnWorkerThread" 
> method but can I relate this to promises? Does V8 provide some API to 
> intercept and replace the promise implementation?

Some additional info is needed because it's not wholly clear to me how
you envision this would work. How exactly is your program using
threads?

A V8 isolate is not reentrant. You can migrate it between threads but
only one thread can enter it (and should hold a v8::Locker to ensure
that it's the only one.)

You have some control over when microtasks (promises) are executed
with isolate->SetMicrotasksPolicy(MicrotasksPolicy::kExplicit) and
isolate->RunMicrotasks().

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8Qm2k699G%3DDXAdLA%2BC_vdfQFYJbU%3DnY8UM1JcF2xccMg%40mail.gmail.com.


Re: [v8-users] How to properly dispose an isolate

2019-12-06 Thread Ben Noordhuis
On Thu, Dec 5, 2019 at 2:55 PM Darin Dimitrov  wrote:
>
> Hello,
>
> I am embedding V8 in my C++ application and I need to create multiple 
> isolates from different background threads.
>
> Here's my workflow:
>
> 1. Create an isolate in the main thread -> this must be a long living isolate 
> (for the entire application lifetime)
> 2. Spawn multiple short living background threads.
> 3. Inside each background thread, create a new isolate using Isolate::New.
> 4. At the end of the thread, call isolate->Dispose.
>
> My question is about properly disposing the short living isolates. I have 
> noticed that if I call the isolate->Dispose() as a final instruction inside 
> the background thread, chances are that subsequent calls to Isolate::New from 
> other threads will return a pointer to an already disposed isolate. Ss a 
> result of this reuse, I get heap-use-after free errors when I try to perform 
> some operations on this isolate.
>
> On the other hand, if I don't call isolate->Dispose() then each call to 
> Isolate::New will return a fresh new pointer, but the memory claimed by this 
> short living isolates will never be reclaimed and is leaking.
>
> So what is the proper way to dispose the isolates? Should the Dispose call be 
> made from the background thread in which the isolate was created, or I need 
> to dispose it from the main thread (in which I have entered the main 
> isolate). I have tried both approaches without luck.

isolate->Dispose() is the right method to call. I don't believe it's
necessary to call it from the same thread (but neither does it hurt)
as long as the isolate isn't in use by another thread, i.e., hasn't
been Enter()'ed.

Use-after-free errors sound fishy. Isolate::New() heap-allocates the
isolate. Are you using a custom allocator?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_tKSV22wa2a81rMDeQcSHSQY_roxoYd3f7BKNqH8R2HQ%40mail.gmail.com.


Re: [v8-users] Embedding V8 into an Electron native app crashes on macOS

2019-11-21 Thread Ben Noordhuis
On Thu, Nov 21, 2019 at 6:10 PM Zoltan B  wrote:
>
> Hi!
>
> I'm running an electron app, that loads native application (using ffi) that 
> renders content into a canvas in electron. This native C++ code has an 
> embedded V8 inside it.
> I'm compiling V8 into dynamic libraries (.dylib files) (use_component_build 
> is set to true).
>
> My issue is that the V8 inside Electron seems to clash with my V8 instance 
> (they are not the same version), but only on macOS.
> If you look at the call-stack below of the segmentation fault, you can see 
> that it begins in libv8.dylib, but ends up somehow in libnode.dylib which I 
> can't really explain.
>
> Thread 16 Crashed:
> 0 libnode.dylib 0x000108306911 0x107c7 + 6908177
> 1 libnode.dylib 0x00010830609c void 
> v8::internal::LookupIterator::Start() + 60
> 2 libv8.dylib 0x000118bbc354 
> v8::internal::JSObject::SetOwnPropertyIgnoreAttributes(v8::internal::Handle,
>  v8::internal::Handle, 
> v8::internal::Handle, v8::internal::PropertyAttributes) 
> + 164 (js-objects.cc:3148)
> 3 libv8.dylib 0x000118a9bc06 
> v8::internal::Genesis::GetThrowTypeErrorIntrinsic() + 118 (handles.h:144)
> 4 libv8.dylib 0x000118a9c13d 
> v8::internal::Genesis::AddRestrictedFunctionProperties(v8::internal::Handle)
>  + 29 (bootstrapper.cc:1109)
> 5 libv8.dylib 0x000118ab1de5 
> v8::internal::Genesis::Genesis(v8::internal::Isolate*, 
> v8::internal::MaybeHandle, 
> v8::Local, unsigned long, 
> v8::DeserializeInternalFieldsCallback, v8::MicrotaskQueue*) + 1269 
> (bootstrapper.cc:5446)
> 6 libv8.dylib 0x000118a9b209 
> v8::internal::Bootstrapper::CreateEnvironment(v8::internal::MaybeHandle,
>  v8::Local, v8::ExtensionConfiguration*, unsigned long, 
> v8::DeserializeInternalFieldsCallback, v8::MicrotaskQueue*) + 89 
> (bootstrapper.cc:5374)
> 7 libv8.dylib 0x0001188862aa v8::NewContext(v8::Isolate*, 
> v8::ExtensionConfiguration*, v8::MaybeLocal, 
> v8::MaybeLocal, unsigned long, 
> v8::DeserializeInternalFieldsCallback, v8::MicrotaskQueue*) + 1722 
> (api.cc:5697)
> 8 libv8.dylib 0x0001188866fa v8::Context::New(v8::Isolate*, 
> v8::ExtensionConfiguration*, v8::MaybeLocal, 
> v8::MaybeLocal, v8::DeserializeInternalFieldsCallback, 
> v8::MicrotaskQueue*) + 42 (api.cc:5856)
>
>
>
> Is it possible that when libv8.dylib loads the subsequent .dylib files with 
> dlopen() (such as libv8_platform.dylib etc.) that dlopen somehow fetches the 
> V8 symbols inside the libnode.dylib?
>
> Electron version I'm using: 1.8.8
> V8 versions I'm using in my app: 7.2 (I tried it with 7.8 too but with the 
> same results)
>
> Could anyone help me out how to avoid this?

Since you're only seeing this on macOS: is anything linked with -flat_namespace?

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_DJMgaCaXin0AmhFCQAj0TijkVaKy5Kwt8zbCFoDWj5A%40mail.gmail.com.


Re: [v8-users] Performance and Resource impacts of using Persistent vs. Local

2019-09-10 Thread Ben Noordhuis
On Tue, Sep 10, 2019 at 9:10 PM Joel Scarfone  wrote:
>
> What is the difference between using an `EscapableHandleScope` to propagate a 
> `Value` and just creating a `Persistent` from the local I intent to return 
> from a function? Is one more performant than the other, or is it just 
> usability?
>
> Joel

EscapableHandleScope is faster. Persistent handles create more work
for the garbage collector.

(That's the pithy version of a longer response I wrote and then
scrapped because of too much details.)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8wggRF%2Bdtk1HrHiWUfc39gMT9cUCft4NRu%3DXwz_LwfxQ%40mail.gmail.com.


Re: [v8-users] How to wrap c++ obj during initialization and unwrap during binded function callback ??

2019-08-19 Thread Ben Noordhuis
On Mon, Aug 19, 2019 at 5:19 PM Sudheer Kumar  wrote:
>
> Hello everyone,
>I am struggling wrapping and unwrapping the c++ object (MYCLASS) . below 
> is the sample code i have written for my exact requirement:
>
>
>   void Update_Rotation(const v8::FunctionCallbackInfo& info);
>
> class MYCLASS {
>  public:
>
>   Point(D_TYPE1 *par1) : rotate(par1) { }
>
>   D_TYPE1 *rotate;
>
>   void run_script()
>   {
> v8::V8::InitializeICUDefaultLocation(argv);
> v8::V8::InitializeExternalStartupData(argv);
> std::unique_ptr platform = 
> v8::platform::NewDefaultPlatform();
> v8::V8::InitializePlatform(platform.get());
> v8::V8::Initialize();
>
> v8::Isolate::CreateParams create_params;
> create_params.array_buffer_allocator = 
> v8::ArrayBuffer::Allocator::NewDefaultAllocator();
> v8::Isolate* isolate = v8::Isolate::New(create_params);
> v8::Isolate::Scope isolate_scope(isolate);
>
> v8::Isolate::Scope isolate_scope(isolate);
>
> // Create a stack-allocated handle scope.
> v8::HandleScope handle_scope(isolate);
>
> // Create a template for the global object.
> v8::Handle global = v8::ObjectTemplate::New(isolate);
>
> /* Here the internal field count is set to 1 which means the object has one 
> internal field, with an index of 0, that points to a C++ object.*/
> global->SetInternalFieldCount(1);
>
> // Bind the 'update_rotation' function
> global->Set(v8::String::NewFromUtf8(isolate, "update_rotation", 
> v8::NewStringType::kNormal).ToLocalChecked(),
> v8::FunctionTemplate::New(isolate, Update_Rotation));
> // Create a new context.
> v8::Local context = v8::Context::New(isolate, NULL, global);
> //Persistent context = v8::Context::New(isolate, NULL, global, 
> nullptr);
>
> // Enter the context for compiling and running the script.
> v8::Context::Scope context_scope(context);
>
> Local obj = global->NewInstance(context).ToLocalChecked();
> obj->SetInternalField(0, External::New(isolate, this));
> /* My JS script */
> v8::Local source = v8::String::NewFromUtf8(isolate, "var 
> rotate_status = 
> update_rotation();",v8::NewStringType::kNormal).ToLocalChecked();
> //exception handler
> v8::TryCatch try_catch(isolate);
>
> printf("Script : compilation started\n");
> // Compile the source code.
> v8::Local script = v8::Script::Compile(context, 
> source).ToLocalChecked();
> printf("Script : compilation compilation done\n");
> printf("Script : Running started\n");
> // Run the script to get the result.
> v8::Local result = script->Run(context).ToLocalChecked();
>   }
> };
>
> void Update_Rotation(const v8::FunctionCallbackInfo& info) {
> Local self = info.Holder();
> Local wrap = Local::Cast(self->GetInternalField(0));
> void* ptr = wrap->Value();
> MYCLASS* temp_sp = static_cast(ptr);   
> //--> Here i am always getting null pointer
> D_TYPE1 *rotate_ptr = static_cast(ptr)->rotate;
>
> rotate_ptr->Update();
> }
>
>
> int main()
> {
> D_TYPE1 *sample_rotate_obj = new D_TYPE1();
> MYCLASS test_obj(sample_rotate_obj);
>
> test_obj.run_script();
> }
>
>
> Can anyone plz suggest how to fix it to get valid pointer to my object?
>
> Thanks in advance ...
>
> Regards
> Sudheer

To summarize what your code does:

1. It creates an ObjectTemplate for the global template.
2. It passes that ObjectTemplate to Context::New()
3. It then creates a new instance of the same ObjectTemplate and sets
its internal field #0.

In other words, two instances are created: once by you, once
(implicitly) by Context::New().

The one you created manually isn't used. When JS code calls your
update_rotation() method, it does so using the instance that
Context::New() created.

I didn't test but calling context->Global()->SetInternalField() might
fix your issue.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8cHNrrvHXHP27c-2vaQ%3DurW6Jg8%2BxLSQSw2HcQbaqaag%40mail.gmail.com.


Re: [v8-users] Is it possible to take snapshot of a running Chrome tab?

2019-07-29 Thread Ben Noordhuis
On Sat, Jul 27, 2019 at 10:44 AM Cong Zuo  wrote:
>
> Hey guys. I wonder if it's possible to take snapshot of a running Chrome tab 
> and using the snapshot blob to start a isolate with Node.js or d8.
>
> All I need is to capture/snapshot user defined objects and functions only, 
> which means external functions like DOM API are not included.
>
> I wrote a simple runtime function called `%TakeSnapshot`, which failed lots 
> of DCHECKs...
>
> After some code searching and test, I don't think it's possible to complete 
> the task with little understanding of the whole project.
>
> Any advises would be appreciated!

The short answer is "you can't."

Snapshots are very closely tied to the environment they were created
in. For example, trying to load a snapshot into Node.js version X that
was created with Node.js version Y almost certainly won't work.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc93ub2EQHGWTXhXyQ1uY9GxbbQteq%2BZa2nUXzt3N77XqA%40mail.gmail.com.


Re: [v8-users] About how long would it be taken to do garbage collection in large memory?

2019-07-29 Thread Ben Noordhuis
On Sun, Jul 28, 2019 at 3:33 PM Marsha  wrote:
> How likely will the time of garbage collection change when the amount of live 
> objects increases? Could it be roughly linearly?
>
> Let's say if 1 million live objects use 10 ms on GC, then could 10 millions 
> live objects use 100~ms on GC?

Yes, it scales roughly linearly.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_L4gmj43AK%2BufQzyK%3D2Ur5BbPwjsBRygFdQxfHRZR2LQ%40mail.gmail.com.


Re: [v8-users] About how long would it be taken to do garbage collection in large memory?

2019-07-28 Thread Ben Noordhuis
On Thu, Jul 25, 2019 at 5:47 PM purple lad  wrote:
>
> I mean the case where an applications uses 1TB memory with tons of live 
> objects. How long might it be taken for the V8 GC to work with the 1TB memory 
> filled with tons of live objects?
>
> The V8 blog shows some data where it might take 100~ms for a normal website 
> (https://v8.dev/blog/concurrent-marking). But I am wondering how the 
> performance will be for some extreme cases (i.e., 1TB heap filled with tons 
> of live objects.)
>
> I know it is really impossible to give an accurate answer. But I just want to 
> get very some basic ideas and estimations for the GC performance for very 
> huge cases. Would the GC time on main thread be milli-second, second or even 
> minutes level?
>
>
> Thank you!

A typical Node.js application often has 10,000s to 100,000s of live
objects. A major garbage collection cycle normally completes in under
10 milliseconds.

(In practice, most will be minor scavenges that complete in < .1 ms.)

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc8WPGNjcU13SPS5-jko0zmT5XNLRqkb6HGJwV3xn_qmLA%40mail.gmail.com.


Re: [v8-users] About how long would it be taken to do garbage collection in large memory?

2019-07-24 Thread Ben Noordhuis
On Wed, Jul 24, 2019 at 6:25 PM Marsha  wrote:
>
> If a node application uses very large  memory (e.g., 512GB, 1024GB etc.), 
> about how long might it be taken to do garbage collection by the latest V8?
>
> Could V8 be trusted to run large in-memory applications?

Your question is poorly phrased. The garbage collector performs work
relative to the _live_ set of objects. Sweeping a 1 TB heap with only
one live object is instantaneous; sweeping a 1 GB heap with 1 million
objects is not. It's impossible to give an accurate answer without
knowing the details of your application.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-iSocRskPWo3%2Bdi2E%2BUE6ZUFy09C5U1NVNejCDq3jcmw%40mail.gmail.com.


Re: [v8-users] Limit execution time to 1ms

2019-07-16 Thread Ben Noordhuis
On Tue, Jul 16, 2019 at 2:29 PM Jaka Jančar  wrote:
>
> On the motivation: I have user-provided (synchronous, relatively simple) 
> snippets of code that run 1k+ times/second on a server and must execute very 
> predictably and fast or they can affect the rest of the system/users.
>
> I'm using timer_create() with SIGEV_THREAD indeed (so not really managing my 
> own thread). Perhaps SIGEV_THREAD_ID would be faster, because there is no 
> scheduling/switching between two threads involved, but I was under the 
> impression that functions need to be async-signal-safe for that as well, just 
> as for SIGEV_SIGNAL. Can you explain why you think that is not the case?

With SIGEV_THREAD_ID you can just block the signal with
pthread_sigmask() and then wait race-free for delivery with
sigwaitinfo().

Having said that, unless there are other reasons to use timer_create()
or signals, it's probably easier to suspend with nanosleep() or
clock_nanosleep().

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_7CwTdkvzTVCmHFP6xRa2%2B3E-xoftcbXCq6hbyz3GKvQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] Limit execution time to 1ms

2019-07-16 Thread Ben Noordhuis
On Tue, Jul 16, 2019 at 1:43 AM Jaka Jančar  wrote:
> Hi,
>
> Is there any way to limit execution time to 1ms? Calling timer_create() and 
> RequestTermination() from another thread is ok for double-digit timeouts, but 
> not high resolution enough for single digit ones. Is there some callback on 
> isolate thread that could be used for clock_gettime()?
>
> Jaka

There's no such mechanism. I suppose you could blast the JS thread
with `isolate->RequestInterrupt(callback, data)` calls but that would
be very inefficient.

Since you're already using a watchdog thread, can't you nanosleep()
for approx. 997 usec and call `isolate->RequestTermination()`? If that
isn't precise enough, can you elaborate on why you need that kind of
resolution?

Aside: if you're using timer_create() with the SIGEV_SIGNAL flag, keep
in mind that `isolate->RequestTermination()` is _not_
async-signal-safe. SIGEV_THREAD or SIGEV_THREAD_ID is okay though.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-ZSB1aNRWjJE_s6FyiHZjCV%3D37ecNLefj2wWRMtNgOpQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] Embedding V8 - Forcing strict mode

2019-07-12 Thread Ben Noordhuis
On Thu, Jul 11, 2019 at 9:47 PM Joel Scarfone  wrote:
> Is there a way from the embedder's side to force a script to be compiled in 
> strict mode?

There's a `--use_strict` flag you can pass on the command line or
through V8::SetFlagsFromString() but it's a global setting.

If you load a script as an ES module, it's always executed in strict mode.

Last but not least, you can always prepend the script code with a
`'use strict';`. That will throw off line numbers in error messages
but you might be able to fix that by passing in a ScriptOrigin with
its line offset set to -1.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9RwXK9sFi20W%2Bsj_SJ8rP3ZwN-uwc7U9%2BRdFH1yudDAg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] Keep v8 context alive for future reference

2019-06-27 Thread Ben Noordhuis
On Thu, Jun 27, 2019 at 5:05 AM Austin Einter  wrote:
>
> Dear All
> I am quite new to v8. I am a c developer, with limited c++ knowledge. Sorry 
> if I ask very basic questions.
>
> I have a C application, that interacts with web servers. Gets javascript. 
> Need to execute javascript.
> Imagine a situation, where I get total 2 javascript files from server.
>
> js1.js
>
> function js_add_elements(var1, var2)
> {
> var var3 = parseInt(var1) + parseInt(var2);
> var result = 'Addition of ' + var1 + ' and ' + var2 + ' results ' + var3;
> return result;
> }
>
>
> js2.js
>
> js_add_elements(2, 3);
>
>
>
> I have my c code as below.
>
> Header file
> typedef struct
> {
> std::unique_ptr platform;
> v8::Isolate::CreateParams create_params;
> v8::Isolate *isolate;
> v8::Isolate::Scope *isolate_scope;
> }MJSEInstance;
>
> #ifdef __cplusplus
> extern "C" {
> #endif
>
> /**
> * @brief Create MJSE instance
> */
> void *mjse_create_instance(char **argv);
>
> /**
> * @brief Destroy MJSE instance
> * @param instance -> MJSE instance
> */
> void mjse_destroy_instance(void *instance);
>
> /**
> * @brief Executes a script
> * @param minstance - MJSE instance
> * @param jscript - the javascript
> * @param scriptlen - Length of script
> */
> void mjse_execute_script(void *instance, char *jscript);
>
> #ifdef __cplusplus
> }
> #endif
>
> CPP File
> #include 
> #include 
> #include 
> #include "include/libplatform/libplatform.h"
> #include "include/v8.h"
> #include "mjse.h"
> #include "mjse_int.h"
> #include 
>
> extern "C"  {
> using namespace v8;
>
> void *mjse_create_instance(char **argv)
> {
> MJSEInstance *instance = (MJSEInstance *)calloc(1, sizeof(MJSEInstance));
>
> v8::V8::InitializeICUDefaultLocation(argv[0]);
> v8::V8::InitializeExternalStartupData(argv[0]);
> instance->platform = v8::platform::NewDefaultPlatform();
>
> v8::V8::InitializePlatform(instance->platform.get());
> v8::V8::Initialize();
>
> instance->create_params.array_buffer_allocator = 
> v8::ArrayBuffer::Allocator::NewDefaultAllocator();
> instance->isolate = v8::Isolate::New(instance->create_params);
> instance->isolate_scope  = new v8::Isolate::Scope(instance->isolate);
>
> return instance;
> }
>
> void mjse_destroy_instance(void *minstance)
> {
> MJSEInstance *instance = (MJSEInstance *)minstance;
>
> if(instance == NULL)
> return;
>
> if(instance->isolate_scope)
> {
> delete instance->isolate_scope;
> }
>
> if(instance->isolate)
> {
> instance->isolate->Dispose();
> }
>
> v8::V8::Dispose();
> v8::V8::ShutdownPlatform();
>
> if(instance->create_params.array_buffer_allocator)
> {
> delete instance->create_params.array_buffer_allocator;
> }
>
> instance->~MJSEInstance();
> free(instance);
> }
>
>
> void mjse_execute_script(void *minstance, char *jscript)
> {
> MJSEInstance *instance = (MJSEInstance *)minstance;
>
> // Create a stack-allocated handle scope.
> v8::HandleScope handle_scope(instance->isolate);
>
> // Create a new context.
> v8::Local context = v8::Context::New(instance->isolate);
>
> // Enter the context for compiling and running the hello world script.
> v8::Context::Scope context_scope(context);
>
> {
>
> // Create a string containing the JavaScript source code.
> v8::Local source =
>   v8::String::NewFromUtf8(instance->isolate, jscript,
>   v8::NewStringType::kNormal).ToLocalChecked();
>
> // Compile the source code.
> v8::Local script =
>   v8::Script::Compile(context, source).ToLocalChecked();
>
> // Run the script to get the result.
> v8::Local result = script->Run(context).ToLocalChecked();
>
> // Convert the result to an UTF8 string and print it.
> v8::String::Utf8Value utf8(instance->isolate, result);
> printf("%s\n", *utf8);
> }
> }
> }
>
> Main File
> int main(int argc, char **argv)
> {
> char *script;
> void *instance;
>
> instance = mjse_create_instance(argv);
>
> script ="function js_add_elements(var1, var2) \
> { \
> var var3 = parseInt(var1) + parseInt(var2); \
> var result = 'Addition of ' + var1 + ' and ' + var2 + ' 
> results ' + var3; \
> return result; \
> };";
> mjse_execute_script(instance, script);
>
> script = "js_add_elements(2, 3);";
> mjse_execute_script(instance, script);
>
> mjse_destroy_instance(instance);
> return 0;
> }
>
> Now whats happening, while executing javascript first time it executes fine. 
> But while trying to execute second time (letter in red), it gets exception.
>
> I understand, it is creating new v8 Local context each time, and does not 
> have js1.js details, hence getting exception. I also found in web we can have 
> v8 Global context and refer the context while executing 

Re: [v8-users] Associate custom C++ data with a Local instance

2019-06-13 Thread Ben Noordhuis
On Thu, Jun 13, 2019 at 11:05 AM Darin Dimitrov
 wrote:
>
> I am trying to associate some custom C++ data with a Local instance.
>
> Currently I am able to achieve this only to instances created with this 
> function:
>
> Local tmpl = FunctionTemplate::New(isolate, [](const 
> FunctionCallbackInfo ) {
> Isolate* isolate = info.GetIsolate();
> // Associate some custom C++ data with the instance created through this 
> function
> info.This()->SetInternalField(0, External::New(isolate, nullptr));
> });
> tmpl->InstanceTemplate()->SetInternalFieldCount(1);
> Local func = tmpl->GetFunction(context).ToLocalChecked();
>
> Local instance = func->NewInstance(context).ToLocalChecked();
> // Getting back the C++ data associated with the instance
> Local extData = instance->GetInternalField(0).As();
>
> What I would like to achieve is to associate the function instance with 
> custom data:
>
> func->SetInternalField(0, External::New(isolate, nullptr));
>
> But unfortunately this throws an "Internal field out of bounds error".
>
> Is it possible to achieve this?

Yes, you can. Put the External on the Function with
Function::SetPrivate(). You can then retrieve it again with
Function::GetPrivate(). Create the Private key with Private::ForApi().

GetPrivate() and SetPrivate() are inherited from Object so it works
for Objects, Arrays, Maps and Sets as well.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9QnFDOdzKGWCpYJ3%3DixZizo_LhcTdEKZ8NLTwHzpM4SQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] How to intercept the context changing operation for JS code in v8

2019-06-01 Thread Ben Noordhuis
On Tue, May 28, 2019 at 4:14 PM Luo Wu  wrote:
>
> I'm trying to understand the connection between them. Can I say that all JS 
> function calls will go through MacroAssembler::InvokeFunctionCode? And what I 
> need to do is to instrument that function? Or maybe I can leverage the 
> Runtime::kDebugOnFunctionCall?
>
> Thank you.

Looking at the code, I'd say that, yes,
MacroAssembler::InvokeFunctionCode() is probably the method you want.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_ay0zDJvRVZYeocVM9hpQ%3D7HRxvccG7_Qit3Ygcymv%2BA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] How to get ObjectTemplate in a previous created context?

2019-06-01 Thread Ben Noordhuis
On Sat, Jun 1, 2019 at 7:43 AM Jian Guo  wrote:
>
> I want to wrap a javascript class in v8 embedded.
>
>
> v8::Persistent persistentContext;
> v8::Isolate *pIsolate;
> void init() {
> v8::V8::InitializeICU();
> platform = v8::platform::NewDefaultPlatform();
> v8::V8::InitializePlatform(&(*platform.get()));
> v8::V8::Initialize();
> v8::Isolate::CreateParams create_params;
> create_params.array_buffer_allocator = 
> v8::ArrayBuffer::Allocator::NewDefaultAllocator();
> pIsolate = v8::Isolate::New(create_params);
> auto ft = v8::FunctionTemplate::New(pIsolate);
> ft->SetClassName(v8::String::NewFromUtf8(pIsolate, "MyClass"));
> ft->ReadOnlyPrototype();
> ft->SetCallHandler(MyClass::constructorCallback);
> ft->SetLength(1);
> v8::Eternal v8MyClassConstructor(pIsolate, ft);
> auto global_template = v8::ObjectTemplate::New(pIsolate);
> global_template->Set(v8::String::NewFromUtf8(pIsolate, "MyClass"), 
> v8MyClassConstructor.Get(pIsolate));
>
> // Enter the context for compiling and running the hello world script.
> v8::Local context = v8::Context::New(pIsolate, nullptr, 
> global_template);
> persistentContext.Reset(pIsolate, context);
> }
>
>
>
>
> In my code, after init() being called, I want to wrap more native class to 
> the previous context, what should I do? I want something like:
>
>
> void bindClass() {
> auto ctx = persistentContext.Get(pIsolate);
> auto global = ctx->GetGlobalObjectTemplate(); // No such function, trying 
> to get global_template variable from init() method
> auto ft = v8::FunctionTemplate::New(pIsolate);
>
>   ft->SetClassName(v8::String::NewFromUtf8(pIsolate, "Foo"));
>   // set up another class called "Foo"
>   global->Set(v8::String::NewFromUtf8(pIsolate, "Foo"), ft));
>
>
> }
>
>
> void main() {
>init();
>// some code here...
>bindClass();   // bind more class to global later...
> }
>
>
> Besides, I am puzzled with the global_template concept here, as it is 
> mentioned in the https://v8.dev/docs/embed#templates sample code:
>
> // Create a template for the global object and set the
> // built-in global functions.
> Local global = ObjectTemplate::New(isolate);
> global->Set(String::NewFromUtf8(isolate, "log"),
> FunctionTemplate::New(isolate, LogCallback));
>
> // Each processor gets its own context so different processors
> // do not affect each other.
> Persistent context = Context::New(isolate, NULL, global);

Once the global object is created, it's created - modifying the
ObjectTemplate post hoc won't do anything.

You can still add properties ad hoc through
context->Global()->Set(...) but they won't show up in other contexts,
of course.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc_YqiUZWbZYRg0bqCmT%2BZmb0LVNRAguWHH-fBw8QxTbew%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] How to intercept the context changing operation for JS code in v8

2019-05-28 Thread Ben Noordhuis
On Tue, May 28, 2019 at 11:20 AM Luo Wu  wrote:
>
> Thanks for your reply.
>
> I checked the code related to IsolateAddressId::kContextAddress. In 
> src/builtins/x64/builtins-x64.cc, it seems that the function 
> Generate_JSEntryTrampolineHelper just loads the context but does not 
> overwrites it. I also found that the context is overwrote in 
> MacroAssembler::EnterExitFramePrologue. Is it the one I need to instrument? 
> Or is there any misunderstanding on my part?
>
> If i am right, are all JS function calls (including document.cookie etc) 
> going through that function, or are they just cross-frame function calls?
>
> Thank you.

MacroAssembler::EnterExitFramePrologue() is one place but there's also
the microtask queue (used for things like promises), see
SetCurrentContext() in src/builtins/builtins-microtask-queue-gen.cc.
That file generates machine code ahead-of-time.

NB: You may not need to instrument the AOT code (which is even
trickier than instrumenting runtime generated code) because ultimately
it calls Builtins::Generate_CallFunction() and that function also
loads the context from JSFunction::kContextOffset.

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc9MfWyYPWb-wCBS5GO5Mst_g_Dv8%3DiSyR2AYXsu6ZYJHg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] How to intercept the context changing operation for JS code in v8

2019-05-27 Thread Ben Noordhuis
On Sat, May 25, 2019 at 11:34 AM Luo Wu  wrote:
>
> Hi all,
>
> I want to intercept and log the context changing event in v8.
>
> Say I have a script in main.html which invokes a function foo in the 
> iframe.html. When the function foo is executed, the isolate->context() is 
> changed to represent for iframe.html. But I cannot find where the v8 sets the 
> corresponding context variable (isolate->set_context() is not invoked). My 
> purpose is to immediately know that the context is changed, and log some 
> information.
>
> Please tell me how can I achieve this goal. Appreciate if there is any idea 
> for that.

The short answer is that you can't, at least not easily.

The context is changed directly from the generated machine code, there
is no associated C++ function call that you can instrument. Grep
src/builtins/*/builtins-*.cc for IsolateAddressId::kContextAddress and
IsolateAddressId::kPendingHandlerContextAddress to find out how it
works.

It's possible to augment the generated code to call out to a C++
function but it's not exactly trivial. Grep the aforementioned files
for CallCFunction() and note how e.g.
Runtime::kUnwindAndFindExceptionHandler corresponds to
Runtime_UnwindAndFindExceptionHandler in
src/runtime/runtime-internal.cc. Good luck!

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-Ljw0SJiGqV5ZJQxfe4OjKOBJre4qi82L2wQHgMfXk_g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: [v8-users] Compile in icudtl.dat

2019-05-23 Thread Ben Noordhuis
On Tue, May 21, 2019 at 8:45 PM Joel Scarfone  wrote:
> I do not want to have to include icudtl.dat on the machine running my 
> executable that i have v8 embedded in to achieve the EXMAScript 402 
> specification (going off of https://v8.dev/docs/i18n). Is there any way to do 
> this?

You can (Node.js does, for example) but I don't know how
well-documented or supported it is. Googling 'icu genccode' doesn't
turn up any hits for me at any rate. :-)

ICU's source/tools/genccode/genccode.c turns the data file into a .c
file that you can compile and link into your final executable or
library. There's a bit of a chicken and egg problem in that genccode.c
itself depends on ICU but you can work around it by linking genccode
to source/stubdata/stubdata.cpp.

I'd refer you to how Node.js builds its embedded copy of ICU but it
also has extra steps to strip unneeded data and such, so it's a little
more complex than what I just described. But if you're interested, the
steps are here:
https://github.com/nodejs/node/blob/165916b1f3ec094b1694bd5a056c2fc5e56027c2/tools/icu/icu-generic.gyp

-- 
-- 
v8-users mailing list
v8-users@googlegroups.com
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to v8-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/v8-users/CAHQurc-gyLSs5zaLrO8hR1cZEdMTqyD8tHDDqTU1mwp_GpzELQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


  1   2   3   4   5   6   7   8   >