phpv8 / php-v8 Goto Github PK
View Code? Open in Web Editor NEWPHP extension for V8 JavaScript engine
Home Page: https://php-v8.readthedocs.io
License: MIT License
PHP extension for V8 JavaScript engine
Home Page: https://php-v8.readthedocs.io
License: MIT License
When V8 exception thrown with an V8 object that has no PHP reference stored, correspondent external exception did not pop up in a final result:
<?php
/** @var \Phpv8Testsuite $helper */
$helper = require '.testsuite.php';
require '.v8-helpers.php';
$v8_helper = new PhpV8Helpers($helper);
$isolate = new \V8\Isolate();
$context = new \V8\Context($isolate);
$v8_helper->injectConsoleLog($context);
$global = $context->globalObject();
$func_tpl = new \V8\FunctionObject($context, function (\V8\FunctionCallbackInfo $info) {
$isolate = $info->getIsolate();
$context = $info->getContext();
$info->getIsolate()->throwException($info->getContext(), \V8\ExceptionManager::createError($context, new \V8\StringValue($isolate, 'test')), new RuntimeException('test'));
});
$global->set($context, new \V8\StringValue($isolate, 'e'), $func_tpl);
try {
$v8_helper->CompileRun($context, 'e()');
} catch (\V8\Exceptions\TryCatchException $e) {
$helper->exception_export($e);
$helper->assert('No external exception present', $e->getTryCatch()->getExternalException(), null);
}
$v8_helper->CompileRun($context, 'try {e()} catch(e) {}');
outputs
V8\Exceptions\TryCatchException: Error: test
No external exception present: ok
It looks like we might need to store reference to exception objects thrown on some isolate-specific stack.
While it reside under v8::V8::WarmUpSnapshotDataBlob()
it should go to StartupData::warmUpSnapshotDataBlob()
I just came across your project and it looks very interesting.
What motivated you to start this project?
What are the pros / cons of php-v8 vs v8js?
Thanks!
Rationale:
As this extension is currently under development and it public API could not be considered as stable and that extension is not yet widely used, such action shouldn't have negative effect on it's users.
If you are using php-v8 extension and for some reason have to stick to PHP 7.0 - please, let me know in comments. If you are willing to upgrade and capable to do that, please, let me know too in comments.
This poll considered to be open for the next two weeks and then will be closed and new version will be released without PHP 7.0 support.
While I want to check if a JS function is a constructor I got this error:
Error
Call to undefined method V8\FunctionObject::IsConstructor()
Input:
class TestClass {
testMe() {
console.log('test me!!!');
}
}
TestClass
Used the return value.
Field | Value |
---|---|
Commit | v8/v8@a787c3f |
Title | Allow overriding DCHECK handling and make it non-fatal. |
Tag | 6.3.163 |
Hi, I have a short question regarding the php-v8 ppa. Iam using this ppa in a docker image which automatically installs this extension. It uses a fixed version i.e. 0.1.3.1-ppa1~xenial
unfortunately if you release a new version it is not possible to install an older version anymore. Basically my docker file looks like:
ENV PHPV8_VERSION "0.1.3.1-ppa1~xenial"
RUN add-apt-repository -y ppa:pinepain/php
RUN apt-get update -y
RUN DEBIAN_FRONTEND=noninteractive apt-get -y install php-v8=${PHPV8_VERSION}
I have updated now my dockerfile to 0.1.6-ppa1~xenial
and everything works fine. But is there a way to install older versions so that my dockerfile does not break directly if you release a new version?
After we update v8 dependency to 6.3, we have to implement this change.
Related commits in v8:
"Use NewDefaultPlatform instead".
Hei, so much respect for this library it's awesome :)
I got it to work and wrote a wrapper arround it after lot of experiments and It was educational, will publish it soon.
I have a question regarding modules. I want to use modules on the common js way like in node.js.
I saw some hints in the php stub about modules, but I don't know how to get it to work.
Is this already working? If yes, can you give me any hints how to implement some easy usecases?
Thank you very much!
Message::isSharedCrossOrigin()
and Message::isOpaque()
are effectively duplicating methods from ScriptOriginOptions
, which could be retrieved as Message::getScriptOrigin()->options()
.
As we don't strictly follow V8 C++API, we don't need them.
While we have all that in PHP, it might come in handy under certain circumstances to use V8's JSON::stringify()
and JSON::parse()
.
For those who want to contribute: this task is easy to pick - just draw inspiration from existent php-v8 code style. V8's JSON
class is very simple and it has just two static methods, which should be also static in PHP: https://github.com/v8/v8/blob/6441d234c4148e8e34a623ba3e5861a451737ffc/include/v8.h#L1799-L1829
Name | Value |
---|---|
Since v8 version | 6.3.215 |
Commit hash | v8/v8@7f9de3d |
Chromium issue | https://bugs.chromium.org/p/chromium/issues/detail?id=768705 |
[snapshot] add kProduceExhaustiveCodeCache option.
- Add kProduceExhaustiveCodeCache to v8::ScriptCompiler::CompileOptions
to request eager compilation to add as much as possible to the code
cache for the script.- Repurpose ParseInfo::kLazy flag.
- Remove ParseInfo::kDebug flag.
- Remove --serialize-toplevel as it has become obsolete.
FTR, in fact it is kProduceFullCodeCache
, not kProduceExhaustiveCodeCache
as stated in commit message, see CR issue for details.
[regexp] Add support for dotAll flag
The dotAll flag changes behavior of the dot '.' character to match every
possible single character instead of excluding certain line terminators.
The implementation is staged behind --harmony-regexp-dotall.
Spec proposal: https://github.com/mathiasbynens/es-regexp-dotall-flag
BUG=v8:6172
Review-Url: https://codereview.chromium.org/2780173002
Cr-Commit-Position: refs/heads/master@{#44295}
Since: 5.9.144
Back in #67 CallbackInfo
parent class was removed from FunctionCallbackInfo
and PropertyCallbackInfo
. As both these classes provides somehow the same base interface, for end-user it might be a good idea to abstract from implementation and depend on interface.
Hi, first let me say that this project is really great. It looks like the repo for the php stubs (https://github.com/pinepain/php-v8-stubs) is empty so it is not possible to install the stubs through composer. I have played a bit with the extension and build a small lib (https://github.com/apioo/psx-v8) where I would like to use these stubs as composer dev dependency.
FunctionCallbackInfor
and PropertyCallbackInfo
are completely different by their meaning to a degree that from OOP point of view they are separate entities (like rectangle and square). While I introduced CallbackInfo
long time ago it may create confusion to end-users, so removing it should make overall api more sustainable.
This changes is BC compatible.
Template::set()
$value
could be one of PrimitiveValue
or Template
instance. Both of them extends meta-class Data
. While there is already an internals type check for that, restricting $value
to accept only Data
instances will improve overall method interface and allow users to catch type errors early.
This would be API breaking change.
Current naming creates ambiguity with PHP exceptions and class static methods should be named more verbose.
Move ScriptCompiler\CompileOptions
constants to ScriptCompiler
class.
That separate class makes no sense since we are moving to simplified API.
They are often not needed (especially Isolate) and object's Context could be used instead. The Isolate and Context parameter appeared during mimicking V8 API where this parameter was largely used to deal with lack of function overriding by return type in C++, which is definitely not the case in PHP.
build.log (master branch)
It is possible that I have a problem with V8, but V8Js
ext works fine.
git clone -b alpine/v8-gn https://github.com/AlexMasterov/dockerfiles.git
cd dockerfiles/alpine-v8-lib
or you can just take the result: V8 libs /usr/local/v8
V8_VERSION="5.7.434" \
V8_LIB_SOURCE="https://www.dropbox.com/s/t42mkk5wrfhcoxd/alpine-v8-lib_${V8_VERSION}.tar.gz"
curl -fSL --connect-timeout 30 ${V8_LIB_SOURCE} | tar xz -C
or you can just take my the minimum Dockerfile php 7.0.14.
(RU)
Если что, у меня также есть Skype и Telegram.
Готов в меру сил оказать содействие в решение.
Some methods, e.g. SymbolValue::for()
could be improved, e.g. SymbolValue::createFor()
looks more clear and self-descriptive. There are plenty of a kind. This task is vague by it's nature and in general it requires you to walk through stubs and see what looks strange or what may be hard to understand for end-users and what is not intuitive. BC-breaks are fine at this step.
V8 6.5.28 on Alpine.
The test case from tests/ScriptCompiler_compileFunctionInContext.phpt:
$isolate = new \V8\Isolate();
$context = new \V8\Context($isolate);
$origin = new \V8\ScriptOrigin('test.js', 0, 0, 0, "", new \V8\ScriptOriginOptions(\V8\ScriptOriginOptions::IS_MODULE));
$source_string = new \V8\StringValue($isolate, '"test"');
$source = new \V8\ScriptCompiler\Source($source_string, $origin);
PHP received signal SIGSEGV, Segmentation fault:
0x00007ffff044f5d7 in v8::internal::ModuleDescriptor::Validate(v8::internal::ModuleScope*, v8::internal::PendingCompilationErrorHandler*, v8::internal::Zone*) () from /usr/local/v8/lib/libv8.so
#0 0x00007ffff044f5d7 in v8::internal::ModuleDescriptor::Validate(v8::internal::ModuleScope*, v8::internal::PendingCompilationErrorHandler*, v8::internal::Zone*) () from /usr/local/v8/lib/libv8.so
#1 0x00007ffff091737e in v8::internal::Parser::DoParseProgram(v8::internal::ParseInfo*) () from /usr/local/v8/lib/libv8.so
#2 0x00007ffff091752d in v8::internal::Parser::ParseProgram(v8::internal::Isolate*, v8::internal::ParseInfo*) () from /usr/local/v8/lib/libv8.so
#3 0x00007ffff091bb70 in v8::internal::parsing::ParseProgram(v8::internal::ParseInfo*, v8::internal::Isolate*) () from /usr/local/v8/lib/libv8.so
#4 0x00007ffff052071b in v8::internal::(anonymous namespace)::CompileToplevel(v8::internal::ParseInfo*, v8::internal::Isolate*) () from /usr/local/v8/lib/libv8.so
#5 0x00007ffff05210e2 in v8::internal::Compiler::GetFunctionFromEval(v8::internal::Handle<v8::internal::String>, v8::internal::Handle<v8::internal::SharedFunctionInfo>, v8::internal::Handle<v8::internal::Context>, v8::internal::LanguageMode, v8::internal::ParseRestriction, int, int, int, int, int, v8::internal::Handle<v8::internal::Object>, v8::ScriptOriginOptions) () from /usr/local/v8/lib/libv8.so
#6 0x00007ffff0416513 in v8::ScriptCompiler::CompileFunctionInContext(v8::Local<v8::Context>, v8::ScriptCompiler::Source*, unsigned long, v8::Local<v8::String>*, unsigned long, v8::Local<v8::Object>*) () from /usr/local/v8/lib/libv8.so
#7 0x00007ffff13bc6c4 in zim_ScriptCompiler_compileFunctionInContext (execute_data=<optimized out>, return_value=0x7ffff16131f0) at /tmp/php-v8-0.2.1/src/php_v8_script_compiler.cc:248
#8 0x0000555555b409e4 in ZEND_DO_FCALL_SPEC_RETVAL_USED_HANDLER ()
#9 0x0000555555ae890b in execute_ex ()
#10 0x0000555555b42e78 in zend_execute ()
#11 0x0000555555a9eed3 in zend_execute_scripts ()
#12 0x0000555555a3bc80 in php_execute_script ()
#13 0x0000555555b4508c in do_cli ()
#14 0x0000555555697587 in main ()
v8 6.3 is out and as we stick to the latest v8 version, it's time.
There is also change in late 6.2 (Pass Isolate pointer to String::Utf8Value/Value constructors v8/v8@fe59853 in 6.2.396) we might benefit from and as 6.3 is out there is no major reason against upgrading libv8 dependency.
Following error I got:
Argument 2 passed to V8\ObjectValue::SetAccessorProperty() must be an instance of V8\Function, instance of Closure given
class Message {
const kNoLineNumberInfo = 0;
const kNoColumnInfo = 0;
const kNoScriptIdInfo = 0;
...
class UnboundScript {
const kNoScriptId = 0;
...
As 0
value is ambiguous as vast majority users without strong v8 internals background would be surprised that 0
is not a zero line number, but no info available.
We can safely return/use null to explicitly denote that no info available.
Note, UnboundScript
, StackFrame
and ScriptOrigin
are also affected with this issue, maybe some other too.
It's annoying to have so many boolean args for such primitive thing. As we are walking away to be 1 to 1 binding to V8 C++ API (it's a matter of common sense if you would ask), we don't need this anymore.
ScriptOrigin
and ScriptOriginOptions
are affected.
It could be a list of transitions, what was before and what it become after. Stubs diff may come in handy here.
The only way to grasp and idea how to use php-v8 is to look into tests and/or to have some v8 background, which lowers entrance barrier for newcomers significantly and limits extension real-world adoption.
Important sections:
Isolate
, Context
are;This is a meta issue which denotes important part we are lack of. Actual work needs to be done to properly cover extension API and it usage is much larger and could be a subject of separate issue.
https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata
Some methods , e.g. Script::run()
may return any of Value
types and it comes in handy when IDE could typehint them. There are other methods which offers rich return type variation. As I personally use PhpStorm and it's pretty decent IDE, I'd like to give it first-class support and make more developers happy.
E.g. Promise
is not implemented yet, look into what other classes missed and add support for them
This would be a BC-breaking change.
Rationale is that upcoming php-v8 abstraction library is under development and I want to utilize new PHP 7.2 features, notably, object typehint.
If you are using php-v8 extension and for some reason have to stick to PHP 7.1 - please, let me know in comments. If you are willing to upgrade and capable to do that, please, let me know too in comments.
As of writing, I don't have specific due date for such changes. I guess I will match when top PHP frameworks (Symphony, Laravel) and development tools (xdebug, phpunit, code sniffer, mess detector) and others will fully support PHP 7.2.
It's not clear to me if is possibile like in v8js to call php methods, inject input data and classes inside the js code or get variables outside to interact more.
Is there any documentation?
Hi, I have updated the php-v8 extension to the latest version on ubuntu:
Get:1 http://ppa.launchpad.net/pinepain/php/ubuntu xenial/main amd64 php-v8 amd64 0.1.2-ppa1~xenial [155 kB]
Fetched 155 kB in 0s (515 kB/s)
(Reading database ... 323709 files and directories currently installed.)
Preparing to unpack .../php-v8_0.1.2-ppa1~xenial_amd64.deb ...
Unpacking php-v8 (0.1.2-ppa1~xenial) over (0.1.1-ppa1~xenial) ...
Setting up php-v8 (0.1.2-ppa1~xenial) ...
Now I get the following warning everytime I run a PHP script:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/v8.so' - libv8_libplatform.so: cannot open shared object file: No such file or directory in Unknown on line 0
v8/v8@0ff7b48#diff-3dd7a0f46b1e5c1cc67921449e7180ac
Implement immutable prototype chains
This patch implements "immutable prototype exotic objects" from the ECMAScript
spec, which are objects whose __proto__ cannot be changed, but are not otherwise
frozen. They are introduced in order to prevent a Proxy from being introduced
to the prototype chain of the global object.
The API is extended by a SetImmutablePrototype() call in ObjectTemplate, which
can be used to vend new immutable prototype objects. Additionally, Object.prototype
is an immutable prototype object.
In the implementation, a new bit is added to Maps to say whether the prototype is
immutable, which is read by SetPrototype. Map transitions to the immutable prototype
state are not saved in the transition tree because the main use case is just for
the prototype chain of the global object, which there will be only one of per
Context, so no need to take up the extra word for a pointer in each full transition
tree.
BUG=v8:5149
Review-Url: https://codereview.chromium.org/2108203002
Cr-Commit-Position: refs/heads/master@{#37482}
Since: 5.4.3
Add memory pressure notification API
Based on CL 1777883002.
BUG=chromium:590975
LOG=NO
Review URL: https://codereview.chromium.org/1813963002
Cr-Commit-Position: refs/heads/master@{#35053}
Since: 5.1.215
Hi, I have the case where I define javascript code which defines a number
and on the PHP side I have to differentiate whether the value is an int or float. At the moment all defined numbers are float. I have looked a bit in the source and the check whether to return an integer or float from a number is already implemented (php_v8_value.cc:268
) but commented. Do you have plans to activate this detection? Otherwise I have to perform this check on the PHP side with something like strpos('.', $value) === false ? (int) $value : $value
which I think is not the best solution.
v0.1.9 (released Sept 1, 2017):
v0.2.0 (ETA Sept 14, 2017):
V8\Exception
class as well as it methods is the subject of further renaming;TL;DR
Upcoming release v0.1.9 will be the last release that support PHP 7.0. Starting from v0.2.0 release PHP >= 7.1 required. All comments, requests and suggesting about this should go to #30 issue.
In the upcoming v0.1.9 release I plan to start moving extension public API closer to PHP world which means it become more PSR-2 compatible, especially method names get converted from PascalCase (UpperCamelCase) to typical camelCase (LowerCamelCase) which is not the big issue as PHP is quite lenient to identifiers case. That's not the case for constants, which are often named in camelCase in V8 - I'll rename them to UPPER_UNDERSCORE. Some snake_case methods (notably, HeapStatistics
methods will be renamed to camelCase.
Note, that this list of changes is incomplete, however, I'll try to keep you updated on progress and share further ideas and decisions.
As I'm also developer and a bit in ops, I know how crucial is to have stable API you can rely on and how BC-breaks hurt business.
That's why I have an upcoming surprise for you to let you abstract from v8 internals and just get things done. Stay tuned.
In a while I'll make legacy PPA for those who prefer stability and can't follow current release plan and adapt wild changes.
At the moment some valgrind reports which doesn't look like relevant one to project, one which comes from v8 internals and other which happens only in docker, are suppressed (see #47 for details).
Ideally they should be revisited and validated.
Message::errorLevel()
will require to add MessageErrorLevel
enum class. Look into what other methods missed and add those which make sense from end-user perspective.
After updating some tests become red and reports leaks - https://travis-ci.org/pinepain/php-v8/jobs/271257124.
==16592== Conditional jump or move depends on uninitialised value(s)
==16592== at 0x10B2A5A3: v8::internal::MarkCompactCollector::EmptyMarkingWorklist() (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10B3FE69: v8::internal::MarkCompactCollector::RootMarkingVisitor::VisitRootPointers(v8::internal::Root, v8::internal::Object**, v8::internal::Object**) (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10B0549B: v8::internal::Heap::IterateStrongRoots(v8::internal::RootVisitor*, v8::internal::VisitMode) (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10B2A3AC: v8::internal::MarkCompactCollector::MarkRoots(v8::internal::RootVisitor*, v8::internal::ObjectVisitor*) (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10B267AB: v8::internal::MarkCompactCollector::MarkLiveObjects() (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10B262D7: v8::internal::MarkCompactCollector::CollectGarbage() (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10AF79FA: v8::internal::Heap::MarkCompact() (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10AF5E4A: v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10AF53A1: v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) (in /opt/libv8-6.3/lib/libv8.so)
==16592== by 0x10AF5724: v8::internal::Heap::CollectAllAvailableGarbage(v8::internal::GarbageCollectionReason) (in /opt/libv8-6.3/lib/libv8.so)
I'm not sure was there any changes in v8 internals that affects userland code and thus need some adjustmets or it's a v8 internals issue or it just false-positive. For now I filled a report to v8-users mail lists - https://groups.google.com/forum/#!topic/v8-users/qu1HrjbgRsg.
While we can workaround this issue by simply suppress this issues with valgringrc, it might be a notice of more deeper problem.
"# Fatal error in ../../src/snapshot/snapshot-common.cc, line 286"
"# Version mismatch between V8 binary and snapshot."
"# V8 binary version: 6.3.257"
"# Snapshot version: 6.3.248"
"# The snapshot consists of 1482496 bytes and contains 1 context(s)."
"#"
"Received signal 4 ILL_ILLOPN 7f6b1a7b28e9"
That separate class makes no sense since we are moving to simplified API.
Entering already entered Isolate
and/or Context
is much cheaper, (200% cheaper). Before that we used to wrap a code that did intensive entering and leaving into FunctionObject
callback, which is also overhead and dirty hack. With something like Isolate::withing(callable $callback)
and Context::withing(callable $callback)
it should be more straightforward and much cleaner to let users to do potential optimizations.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.