1192 Commits

Autor SHA1 Mensagem Data
Daniel Sloof 30b0fc0026 headers_list should return array() with no headers
headers_list should return an empty array when there are no
 headers. There were already tests involving this in ext_network.php, but it's
 being skipped (at least in the github repository).

Closes #1218

Reviewed By: @alexmalyshev

Differential Revision: D1030259

Pulled By: @scannell
2013-10-30 11:06:15 -07:00
Brett Simmers 4f78c7de03 Clear out request-local globals at the beginning of each request
The rpc server keeps the ExecutionContext alive across requests to
reduce startup costs. Unfortunately, we weren't clearing $_SESSION, $_GET,
etc... at the beginning of the request. This was making us think that most of
the http headers in most requests were duplicates, and emit a warning where the
option is enabled. It's also generally bad practice to leak this stuff between
different requests.

Reviewed By: @markw65

Differential Revision: D1010456
2013-10-30 11:06:04 -07:00
Paul Tarjan d6a8578e34 try to fix yii again
It turns out the path is unique to my machine. Try glob.

Reviewed By: @JoelMarcey

Differential Revision: D1031707
2013-10-30 11:05:53 -07:00
Paul Tarjan 085f510c23 don't call autoload handler with an empty class
Zend doesn't do it and we shouldn't either. It was causing an assert in a debug build.

Reviewed By: @markw65

Differential Revision: D1030881
2013-10-30 11:05:37 -07:00
mwilliams 1e1eac2a0e Fix fallback when optimized translation fails
analyze needs to read live state, which is only
valid if this is the first tracelet in the region. For
subsequent tracelets, fall back to the interpreter.

Reviewed By: @ottoni

Differential Revision: D1028657
2013-10-30 11:04:53 -07:00
Jordan DeLong 565465d580 Fix slow/intercept tests to pass DynamicInvokeFunctions to compiler
Modify one of the tests so it fails with the wrong options
and pass the right ones, add a similar test for static member
functions.  It appears DynamicInvokeFunction is ignored for member
functions (but member functions are inspected for a "dyn_" prefix??),
so I added norepo for the ones that do intercept on member functions.

Reviewed By: @swtaarrs

Differential Revision: D1029398
2013-10-30 11:03:05 -07:00
Sean Cannella 38be2694ae Fix linking issue on OS X 10.9 with libc++
ld on OS X 10.9 doesn't seem to be able to locate the ctype.h
functions (ex. isdigit) when they are used as function pointers, so wrap
them in lambdas.

Reviewed By: @markw65

Differential Revision: D1030137
2013-10-30 11:02:53 -07:00
Paul Tarjan d87b7c84fb stop yii from see-sawing
yii leaves this file around which is a duplicate of its test. So the autoloader loads it twice. Kill it between runs.

Reviewed By: @JoelMarcey

Differential Revision: D1030682
2013-10-30 11:02:30 -07:00
Herman Venter a8b31881f6 Fix the variable command so that it does not fail totally when one variable is too large.
The variable command, along with its clients the global command and the = command, obtained variable names and values from the server by asking for an map of variable name to variable values in a single request. If one or more of these variables have really large values, the serialization of the map exceeds the serialization limit and the entire command fails. This makes it difficult pin-point which variable causes the trouble and breaks the client commands in unexpected ways.

This diff changes the protocol of the variable command so that it first gets an array of variable names only and then separately gets the value of each variable. If such a separate get fails because of a serialization limit, the variable's value is printed as "...omitted".

Reviewed By: @mikemag

Differential Revision: D1021035
2013-10-30 11:00:11 -07:00
mwilliams bd49a4ac26 Fix retranslateOpt bug
If we've already optimized, we want to do a regular
translation, not an optimized one

Reviewed By: @ottoni

Differential Revision: D1026773
2013-10-30 10:59:14 -07:00
Joel Marcey c33c344f99 fix stream_select error
I am a clown.

Reviewed By: @ptarjan

Differential Revision: D1027352
2013-10-30 10:56:27 -07:00
aravind ec3d41f15f IncRef Sinking fix
An IncRef that is marked as a candidate for sinking should
be removed from the sinking list only if the corresponding DecRefNZ
is live.

Reviewed By: @ottoni

Differential Revision: D1026155
2013-10-30 10:54:54 -07:00
Alex Malyshev afc63c1ab6 Remove incorrect assert
We assert in DOMNode::{appendChild,insertBefore} that the node that
has been passed in is an orphaned node, however it's only orphaned if
it has no parent or its parent is also orphaned.

Fixes the last fatal in yii

Reviewed By: @ptarjan

Differential Revision: D1026211
2013-10-30 10:54:42 -07:00
Paul Tarjan b10c2021e2 set m_documentRoot even if there is no hdf
This variable is entirely independent of the hdf, so it should be set even it there isn't one.

This came up when someone (me) was running `hhvm -m server` from the symphony directory trying to show it off, but PATH_INFO doesn't work unless the m_documentRoot is set. It just assumes that all files exist if there is no document root.

This shouldn't affect anything in FB since there is always a `.hdf`.

Reviewed By: @markw65

Differential Revision: D1025781
2013-10-30 10:54:25 -07:00
mwilliams d04d9ec022 Fix jitted symbols in gdb 7.6
gdb traps calls to a function named __jit_debug_register_code,
and updates its internal symbol tables.

Apparently gdb-7.2 was prepared to demangle the name,
while gdb-7.6 is not.

Reviewed By: aravind

Differential Revision: D1026295
2013-10-30 10:54:10 -07:00
Sean Cannella 5a4db6875a StoreImmPatcher incorrectly handles 64-bit imms
StoreImmPatcher is currently subtracting the wrong offset (not
taking into account the extra instruction emitted) when setting m_addr.

Closes #1210

Reviewed By: @markw65

Differential Revision: D1025861
2013-10-30 10:53:44 -07:00
Bert Maher 251b5d78b4 Fix /stop command issued when hhvm can't bind port
When HHVM can't bind to a port it tries to shut down the
currently running instance using /stop on the admin port, but
RuntimeOption::ServerIP was blank (do we actually set this anywhere?)
and we weren't passing the admin password.

Reviewed By: @markw65

Differential Revision: D944849
2013-10-24 11:53:28 -07:00
Kristaps Kaupe d2ca7292fb Native.h macro typo
Fix macro typo

Reviewed By: @JoelMarcey

Differential Revision: D1023850

Pulled By: @scannell
2013-10-24 11:53:12 -07:00
Franck STAUFFER ebb9f3cadd row_count properly set on INSERT/UPDATES
Fixes bug due to variable shadowing

Closes #364

Reviewed By: @JoelMarcey

Differential Revision: D1021780

Pulled By: @scannell
2013-10-23 13:24:37 -07:00
Paul Tarjan b9d8d0ff47 fix ASAN bug in JSON parser
Wow, our json parser has diverged so much from zend. This is basicaly what theirs does. More importantly, this is correct.

Sadly I don't think is the memory corruption bug.

Reviewed By: @scannell

Differential Revision: D1021678
2013-10-23 13:24:08 -07:00
Herman Venter 73f16bc03b Fix list command so that it finds the right start line and it can find systemlib.php
The list command was using the the string "line2", cunningly disguised as the static string variable 'line1' to look for the line where a func/class/method starts. Also, the file name it got for systemlib.php was expected to always be exactly "systemlib.php" but it turns out this is no longer the case, or at least not always.

Reviewed By: @mikemag

Differential Revision: D1018535
2013-10-22 12:17:20 -07:00
Matthias Eck 540cac6ec2 Fixed step to skip generated functions
Changed cmd_step to check at onBeginInterrupt if the file line is empty i.e. returns as ":0"
In this case continue stepping

Reviewed By: @mikemag

Differential Revision: D1017420
2013-10-22 12:16:59 -07:00
Sara Golemon c20fcce91b Add missing define
Branch has some commits piled onto a non-fix diff on master.
They only really need this one line to work.
2013-10-21 21:37:38 -07:00
Yuval Hager 922a61dad5 Fix Buffer Overrun messages for tiff files
While processing tiff tags, the end pointer was not updated
after a realloc. Also, while processing IFD tag, end and begin pointers
were switched.

Closes #1154
Closes #1193

Reviewed By: @ptarjan

Differential Revision: D1019738

Pulled By: @scannell
2013-10-21 15:38:06 -07:00
Sean Cannella a568ad1a07 Import php-src pull #479
Fix clowny error in zend-strtod.cpp on ARM platforms that passed through the PHP internals mailing list

Reviewed By: @JoelMarcey

Differential Revision: D1019758
2013-10-21 15:37:29 -07:00
Sean Cannella 5815d21518 Fix ICU compliation when not using 51.x
'brew update' to a newer icu4c on OS X exposed that we aren't
being consistent in how we include it resulting in linker errors due to
confusion regarding what the icu namespace is.

Reviewed By: @sgolemon

Differential Revision: D1019529
2013-10-21 15:36:00 -07:00
Anton Grbin 757c1414f5 ArrayInit constructor ssize_t -> size_t
In ArrayInit constructor, n is defined as ssize_t, but negative values
are not handled in any way. We should point that out to callers by
making n of type size_t.

Reviewed By: @edwinsmith

Differential Revision: D1017631
2013-10-21 15:35:42 -07:00
Jordan DeLong a1745fb58b Fix a bug in AGet{L,C} and simplifyLdCls
If AGetL throws due to autoload failure (e.g. parse time
fatal), we crash in the unwinder.

Reviewed By: @bertmaher

Differential Revision: D1018048
2013-10-20 23:22:15 -07:00
aravind 20f0306dd3 Fixes for PGO mode
This fixes a couple of asserts I hit running www in DEBUG mode with
-vEval.JitPGO=1 -vEval.JitRegionSelector=hottrace
-vEval.JitPGOHotOnly=0.

Reviewed By: @ottoni

Differential Revision: D1016284
2013-10-19 00:37:51 -07:00
Alex Malyshev 8121dbb0d3 Fix three eval() bugs
* @ eval() was not being silenced correctly
* If the string passed to eval() hits a parse error, then the runtime
  is not supposed to fatal. We currently do.
* Errors in eval() code did not print a valid file name, they now
  print it as "$FILENAME($LINE1) : eval()'d code on line $LINE2"

Closes #945

Reviewed By: @jdelong

Differential Revision: D1006603
2013-10-19 00:37:41 -07:00
seanc 1177492d76 Fix CMake warning
Summary: Latest CMake on OS X with brew surfaced this warning and that
this check was not doing what it was originally intended to do.
2013-10-19 00:37:21 -07:00
Jordan DeLong 23cd8e033e Fix a bug in TypeConstraint::isSoft
This function returned true if the type had isHHType(), which
it will always if EnableHipHopSyntax=1.  The flag was 0x16 instead of
0x10, and isSoft() just does return m_flags & Soft.

Reviewed By: @dariorussi

Differential Revision: D1014812
2013-10-17 23:44:08 -07:00
Alex Malyshev 6050afa844 Emit an error message when our PHP systemlib doesn't compile
Fixes the terrible "Undefined interface: arrayaccess" error message

Reviewed By: @jdelong

Differential Revision: D1014257
2013-10-17 23:43:56 -07:00
mwilliams 98a2c6ede2 Fix TranslatorX64::m_mode
We need to ensure that m_mode is reset after each
translation attempt.

There was already code in TranslatorX64::translate to reset
it, but after setting it in TranslatorX64::retranslateOpt,
its not certain that we'll get there.

Reviewed By: @swtaarrs

Differential Revision: D1012330
2013-10-17 23:43:43 -07:00
James Miller e766a8a4ac Make the embedded systemlib a dependency of the binary 2013-10-17 23:43:23 -07:00
James Miller 5b7366968a Fix broken make install behaviour
CMake uses rpath to make it easier to run built executables from the build
tree without installing prerequisite libraries first. This means that when
installing, CMake will re-link the binary in order to change the rpath so
it works properly in an install. Unfortunately, it's not smart enough to know
to re-embed the systemlib section, so the installed `hhvm` binary does not
have a systemlib section and doesn't work.

This commit adds a cmake function `HHVM_INSTALL` that effectively bypasses the
standard install command to ensure that the binary is not relinked. To help
with rpaths, this also checks for the existance of the `chrpath` tool. If it
exists, it uses it to either remove or replace the rpath entry in the file,
otherwise it just leaves the rpath entry alone.

This allows `make install` to work again.
2013-10-17 23:42:56 -07:00
Sara Golemon 2d963c4ffb 2.2.0 release 2013-10-16 11:17:06 -07:00
Sara Golemon b413c90e23 Tabs, not spaces 2013-10-16 11:16:10 -07:00
Sara Golemon c29787e69a Disable libnuma support (for now)
See comment in hphp/util/CMakeLists.txt for explanation of why
2013-10-16 10:12:09 -07:00
Sara Golemon 5cae789c57 Simplify HHVM_LINK_LIBRARIES 2013-10-16 09:48:41 -07:00
Eugene Letuchy bc847b8522 make ()-invoke work on array callables (jit)
JIT counterpart to {D984939}. Relies on a similar
 partially-populated JIT-allocated ActRec passed to a C++ helper
 technique used by methodCacheSlowPath.

Reviewed By: @jdelong

Differential Revision: D999262
2013-10-16 09:31:44 -07:00
Drew Paroski 514d815bb5 Fix JIT helpers for isset() on collections
The JIT helpers for isset() were erroneously returning true when a key was
present in a collection but the corresponding value was null. This diff
fixes the helpers appropriately.

Reviewed By: @elgenie

Differential Revision: D1013006
2013-10-16 09:31:39 -07:00
Nathan Bronson bb1742f632 avoid undefined __builtin_clz(0) behavior in nextPower2
HPHP::Util::nextPower2(1) ends up calling __builtin_clz(0),
which has undefined behavior.  In practice it can return any result.
None of the current callers seem to trigger the bug, but in addition to
fixing the bug this diff also reduces the compiled size and increases
the performance of the method.

Also, the attempt to use an arithmetic exception instead of an assert
doesn't seem to be working, so I replaced it with a regular assert.

Reviewed By: @andralex

Differential Revision: D1007106
2013-10-16 09:31:32 -07:00
Eugene Letuchy ce14d3142f disallow more than one of private protected public
... because come on now.

Reviewed By: @paroski

Differential Revision: D1012429
2013-10-16 09:31:28 -07:00
Eugene Letuchy 166da944af easy: parse error for "abstract async"
async is meaningless in an abstract context, since it
 modifies the meaning of the method body.

Reviewed By: @jano

Differential Revision: D1011051
2013-10-16 09:31:24 -07:00
Dario Russi dc12168af0 IR support for collection initializer
Expose to IR the opcodes for initialization of collection

Reviewed By: @paroski

Differential Revision: D1010966
2013-10-16 09:31:20 -07:00
Alok Menghrajani 627c315940 Log when a nullable (e.g. ?int) is incorrect.
Reviewed By: @dariorussi

Differential Revision: D928297
2013-10-16 09:31:16 -07:00
bsimmers 56878d98c5 More hhir guard relaxation fixes and tuning
- Relax more guards as a result of assertions from static analysis
- Add support for using DataTypeGeneric with PopC and friends
- Get guard relaxation-specific logic out of reflowTypes
- Refine/relax some type constraints
- Misc small bugfixes found along the way

Reviewed By: @bertmaher

Differential Revision: D988172
2013-10-16 09:31:11 -07:00
bsimmers 8df1f775ad Clean up MInstrEffects::init
I was running into issues with complicated union types, so I decided
to clean this up a bit. Because the member helpers always operate on the inner
cell of a boxed type, we can just handle the inner type and outer type
separately, simplifying a few things.

Reviewed By: @markw65

Differential Revision: D1005835
2013-10-16 09:31:07 -07:00
Drew Paroski e973549d94 Disallow 'yield' inside an async function
HHVM has checks to make sure that 'yield' and 'await' are not both used
within in the same function/method body. However, HHVM was lacking a check
to make sure that 'yield' was not used inside a function decorated with the
'async' keyword. This diff adds the appropriate check for this, and it adds
some tests.

This check currently will attribute the parse error to the closing curly
brace of the function body. We can fix this later by adding the necessary
plumbing, but I wanted to get a quick fix out for now.

Reviewed By: @elgenie

Differential Revision: D1012387
2013-10-16 09:31:03 -07:00
Paul Tarjan 19b5574e99 support -d for php wrapper
The most commonly used option

Reviewed By: @JoelMarcey

Differential Revision: D1009266
2013-10-16 09:30:55 -07:00
Paul Tarjan 726000a60c start supporting php.ini files
So, I want to make `-d` work from the command line. I tried to make a `IniSettings` section of the `hdf` but it turns out you can't have `.`s in any of the names or else it makes it a nested config section and `.get()` won't traverse it. Supporting a `IniFile` was much easier.

I set a default in `/etc/hhvm/php.ini`. Thoughts?

Reviewed By: @markw65

Differential Revision: D1009092
2013-10-16 09:30:51 -07:00
Jordan DeLong dd4bd0c175 Check for stack overflow when doing include ops
Bsimmers found it.

Reviewed By: @markw65

Differential Revision: D1011987
2013-10-16 09:30:46 -07:00
Joel Marcey 2d166e36ad Improve OSS Framework Unit Testing Script
Added mechanism to print out csv summary results for use in charting (--machine option). Using this option supresses all output except for the csv at thee end.

Show tests that do not give the expected output compared to a previous run.

Enhance help to describe what the colors mean for . and F during test runs.

Add a count of tests that will be compared.

Reviewed By: @ptarjan

Differential Revision: D1010936
2013-10-16 09:30:42 -07:00
seanc e1e1d4a024 Fix jemalloc version check
Summary: The jemalloc version check needs to add the include directory
for jemalloc when compiling or it will incorrectly not find jemalloc in
some cases (ex. OS X.)

Reviewed By: @edwinsmith
2013-10-16 07:41:40 -07:00
Sara Golemon e9cb6bea0d Test for jemalloc >= 3.0.0 before using 2013-10-15 19:04:34 -07:00
Sara Golemon 5f1e277bba Add jemalloc include dir during build 2013-10-15 18:35:47 -07:00
Jordan DeLong 431ef81e51 Specify Strlen opcode
This looks left out.

Reviewed By: @oyamauchi

Differential Revision: D1009227
2013-10-15 13:09:51 -07:00
Jordan DeLong 6d240bfa2c Some {W,}Iter{Init,Next}{K,} spec tweaks
The spec claimed these instructions stored to locals "as a
cell", which sounded to me like it should convert KindOfRef locals
into KindOfCell.  What it meant is that it stored using a normal
assignment (we don't really specify how these work, so I just changed
it to say "with the semantics of SetL").  Also hoist discussion of the
assignment semantics out of the switch (%1) part of the spec.

Reviewed By: @edwinsmith

Differential Revision: D1009178
2013-10-15 13:09:51 -07:00
Jordan DeLong 160646ec9d Clear up a tiny bit of dead logic/code relating to merge-only units
A couple unused variables/functions, and the mainReturn logic
sets up mainReturn even if you don't have a merge only unit, which I
don't think we should require, so changed it to make getMainReturn
require isMergeOnly as a precondition.  (We could maybe indicate
merge-only-ness by whether the mainReturn is KindOfUninit later
instead of the bool.)

Reviewed By: @markw65

Differential Revision: D1009053
2013-10-15 13:09:51 -07:00
Mike Magruder 78f4ef0d2e Coalesce async functions in hotprofiler output
Generators and async functions become two functions when we compile them: the original function, and another with $continuation on the end of the name. With classic generators the original function is a mere stub which returns a Continuation which will use the $continuation function. That's not too interesting from a  profiler perspective: the original function does pretty much no work. For Async, though, the original function may do significant work before the first await, and may even continue to do work depending on the disposition of the object awaited upon.

The hotprofiler extension was separating these two functions and reporting call counts and times separately. While technically correct, it's also pretty useless and in the Async world will hurt since the time spent in such a function is split in some unknown proportion. This will cause users of the data to devalue the const of async functions unless they realize this implementation detail.

This change ensures that all time spent in a generator or async function is aggregated under a single function name: the original one.

Reviewed By: @jano

Differential Revision: D1010450
2013-10-15 13:09:50 -07:00
Paul Tarjan 0a99a266ee make --php emulate zend
If we are going to replace zend, we need a CLI that looks like theirs. This is a start. I'll do `-d` next.

Reviewed By: @markw65

Differential Revision: D1009086
2013-10-15 13:09:32 -07:00
Sean Cannella 0dd561cb8d Fix (non-build-blocking) rebase merge in ref-data.h
"Get rid of refdata_after_decref_helper" added a new call to
smartFreeSize that should be smartFreeSizeLogged.

Reviewed By: @markw65

Differential Revision: D1011305
2013-10-15 12:42:45 -07:00
Sean Cannella 30555198f9 Don't crash on sorting with invalid functions
Right now we crash on the user-defined sort functions if the
function is not valid. Don't do that.

Closes #1165

Reviewed By: @markw65

Differential Revision: D1010050
2013-10-15 12:42:41 -07:00
Sean Cannella e6d6d2c7b7 Wire up heap profiler to memory manager APIs
This wires up the heap tracking APIs to the actual allocation
functions being used.

Reviewed By: @jdelong

Differential Revision: D1007457
2013-10-15 12:42:37 -07:00
Sebastian Bergmann f5879798e1 Fix a typo in bytecode.specfication
Fixes a typo in bytecode.specification

Closes #1173

Reviewed By: @edwinsmith

Differential Revision: D1011297

Pulled By: @scannell
2013-10-15 12:42:33 -07:00
Sean Cannella 5f074e2a9c spl_autoload_call shouldn't overflow guard
Due to Symfony's use of autoload magic, the infinite recursion
detection is a bit too good and breaks their assumption of being able to
autoload circularly in what would overflow the stack if exit() wasn't
involved. Zend allows this so we probably need to as well.

Closes #1170
Closes #1175

Reviewed By: @markw65

Differential Revision: D1009853
2013-10-15 12:42:29 -07:00
mwilliams 18b870a76d Get rid of refdata_after_decref_helper
This made it different from all the other countables,
because instead of calling Foo::release, you had to call
refdata_after_decref_helper.

But the only direct calls to release were either using
it to free the memory (so add releaseMem to do that), or were
already checking m_cow. Rewrite release to check m_cow, which
makes the decRefFoo helpers uniform.

Reviewed By: @swtaarrs

Differential Revision: D1009974
2013-10-15 12:42:24 -07:00
mwilliams f5631b73e2 Fix numa balancing issues
Specifying numa_set_membind doesn't just set the default,
it sets a thread-wide limit on which nodes can provide memory. This
meant that the numa_interleave calls were ineffective.

It turns out that most of the unbalancing occurs during startup/warmup,
so just move the point at which we enable numa.

Reviewed By: @swtaarrs

Differential Revision: D1008356
2013-10-15 12:42:20 -07:00
Paul Tarjan 0564d8a6a8 Make pretty json consistent with zend
They put an empty space on empty things

Reviewed By: @JoelMarcey

Differential Revision: D1010909
2013-10-15 12:42:16 -07:00
Paul Tarjan 5ab0d16a3b allow PharData to get null as the second arg
Reviewed By: @JoelMarcey

Differential Revision: D1010917
2013-10-15 12:42:12 -07:00
Paul Tarjan d6f51ce88a make RecursiveDirectoryIterator::getSubPathname correct
This was just wrong

Reviewed By: @JoelMarcey

Differential Revision: D1010913
2013-10-15 12:42:08 -07:00
Paul Tarjan 64e0abb70d stop being dumb with Phar::getPharAndFile
using a "!" and a "===" are really dumb together. I think the old code was right anyways, but this was crazy.

Reviewed By: @alexmalyshev

Differential Revision: D1008302
2013-10-15 12:42:03 -07:00
mwilliams b8c94828b4 Use hasMultipleRefs rather than refCount > 1
Pretty much mechanical change, which will make it easier
to use the sign bit for RefCountStaticValue.

Reviewed By: @edwinsmith

Differential Revision: D1009397
2013-10-15 12:41:43 -07:00
Dario Russi 7d163cd8f7 Rename APC Shared* and Immutable* objects and files to APC* objects and files
Preparing for a bigger diff we are brining the APC files and objects to a common naming convention

Reviewed By: @jdelong

Differential Revision: D1007981
2013-10-15 12:41:38 -07:00
Owen Yamauchi da534ab41b Even more ARM IR implementations
This takes care of all the quick tests that were hitting
the ##always_assert(!ni->interp)## in translator-x64.cpp. This means
that there all the IR opcodes that appear even when every bytecode is
being interped now have ARM codegen.

The remaining issues in test/quick are primarily complete codegen
failure -- i.e. translateTracelet returns Failure because no amount of
marking bytecodes as "interp" will result in successful codegen. I'll be
going after these next.

Other than that, there are a laundry list of other failures in other
parts of the system, like hhbc-translator, that I don't understand at a
glance. My guess is that interping every bytecode is stressing the
system in a way that exposes some previously-undetected fragility.

Reviewed By: @edwinsmith

Differential Revision: D1005940
2013-10-15 12:41:34 -07:00
Owen Yamauchi 2bddc05951 More ARM implementations
This implement ReqBindJmp and associated machinery, and GuardRefs. It
also moves the jump-target-reading functions out of Asm and into
jump-smash.cpp.

GuardRefs is largely copied, but the codegen logic is nontrivially
different, because of differences like how ARM encodes immediates in
logical instructions, and how it can't do compares and tests with memory
operands.

Reviewed By: @jdelong

Differential Revision: D1005529
2013-10-15 12:41:30 -07:00
Sara Golemon 47cfa24591 Reduce template depth back down to 120 2013-10-15 12:29:04 -07:00
Owen Yamauchi ac8909e223 Fix template explosion in vixl's use of folly::format
This broke the OSS build. I'm just splitting it up into multiple calls,
resulting in more, but less deep, template instantiations.

Reviewed By: @scannell

Differential Revision: D1009550
2013-10-15 12:27:33 -07:00
Owen Yamauchi c12cc3adf2 Get ARM disassembly printing in printir:2
I'm getting to the point where it's helpful to see the ARM code being
emitted, and this is the most natural way to hook it up.

There's a little wrinkle here in that sometimes (e.g. smashable jumps),
there's stuff in the TC that isn't executable code. In this case the
disassembly is either "Unallocated" or some nonsense instruction. We
could avoid this with sufficient metadata, but I'm not convinced it's
necessary yet. (FYI, this pattern -- data embedded in code -- is common
in ARM code, to judge by the vixl assembler's inclusion of an
abstraction to do this very thing.)

In the process I had to convert vixl's printing facilities to use
std::ostream instead of FILE*. I converted it to use folly::format
instead of fprintf as part of this.

Also added an --arm flag to hhvm_wrapper.php to make my life easier.

Reviewed By: @edwinsmith

Differential Revision: D1006435
2013-10-15 12:27:20 -07:00
Mike Magruder d1b2133cf5 Update NEWS for Sausage release.
Added a few things I noticed in the git log

Reviewed By: @scannell

Differential Revision: D1009848
2013-10-15 12:26:53 -07:00
Paul Tarjan 82a3d5e2ca small framework runner changes
- Put a newline before the downloading message as it happened in the middle of the line a bunch of times
- Made the comparing message less verbose since it is printed all the time on every runner
- Renamed it "run" and made it execuatble (in line with `test/run`)
- Fixed a warning where the status is empty. Is that right to ignore it?
- Don't always generate `.expect` files
- Similarly, don't always generate the summary file. I don't really understand what you are trying to do with that one being checked in?

I don't really understand how to use this yet. My runs don't seem to give me the thumbs up, so either the expect files are too specific to @JoelMarcey's machine or the tests are flakey. Either way, we can't use this yet.

Reviewed By: @JoelMarcey

Differential Revision: D1009080
2013-10-15 12:25:01 -07:00
Abel Nieto d9ff7b0548 Add materialization methods
We can now convert any collection toFrozenvVector() and FrozenVector to
any collection.

unit tests pass, but show up as "postponed" in phabricator

Reviewed By: @dariorussi

Differential Revision: D1006767
2013-10-15 12:25:01 -07:00
Sean Cannella 1c29eee893 Fix paramter inconsistency for RequestURI
Fix flipped parameters between declaration and definition for
RequestURI.

Closes #1168

Reviewed By: @JoelMarcey

Differential Revision: D1009413
2013-10-15 12:25:01 -07:00
Abel Nieto bec37947d0 Handle magic methods
Implement proper behaviour for:
  * __toString()
  * __get()
  * __set()
  * __isset()
  * __unset()

(unit tests passed, but permanently show up as "postponed)

Reviewed By: @dariorussi

Differential Revision: D1006156
2013-10-15 12:25:00 -07:00
Abel Nieto ad3f344d9b Support array-style access
Now we can do:

  $fv = FrozenVector {1, 2, 3};
  $x = $fv[0];

Reviewed By: @paroski

Differential Revision: D988684
2013-10-15 12:25:00 -07:00
Sean Cannella f3e60872d6 Fix printf warning on OS X
printf type mismatch warning on OS X (%ld for int64_t is not
true there)

Reviewed By: @edwinsmith

Differential Revision: D1009391
2013-10-15 12:25:00 -07:00
mwilliams 14fb836fdc posix_madvise(..., POSIX_MADV_DONTNEED) is a no-op
Apparently, there's no exact equivalent in linux, so its
treated as a no-op. What we *want* here, however, is exactly what
linux's madvise does.

Reviewed By: @jdelong

Differential Revision: D1007545
2013-10-15 12:24:59 -07:00
Brett Simmers a1ee28fa40 Don't close std(in|out|err) on request shutdown
BuiltinFile is supposed to be a wrapper around an existing FILE or
file descriptor, so it shouldn't close the underlying stream when being swept.

Reviewed By: @bertmaher

Differential Revision: D994199
2013-10-15 12:24:59 -07:00
Bert Maher f848e5ad92 Allow refcount elimination around ArrayIdx
ArrayIdx was treated as "consumesRC", when it really doesn't.
Also move the decref of the default argument to be explicit in the IR
so it can be paired with preceding increfs.  If the default argument
is, in fact, used, it's the responsibility of the arrayIdx helper to
incref it.

Reviewed By: @swtaarrs

Differential Revision: D1008957
2013-10-15 12:24:59 -07:00
Alok Menghrajani c0abfc29d8 Support checking '@'type (soft types) at runtime.
This diff adds support for checking and raising a warning when a soft type (@Alite404Exception) fails. Soft type hints are useful
when converting code from untyped code (php) to typed code (hack).

Discussion: https://www.facebook.com/groups/165748143439038/permalink/690858800927967/.

Reviewed By: @dariorussi

Differential Revision: D926433
2013-10-15 12:24:38 -07:00
Paul Tarjan 861707112c support CSV in SplFileObject::current
Closes #1160

Reviewed By: @alexmalyshev

Differential Revision: D1008072
2013-10-14 12:22:38 -07:00
Jordan DeLong de4ae3ad50 Rename various typedef' things to type alias'
Reviewed By: @swtaarrs

Differential Revision: D1008398
2013-10-14 12:22:34 -07:00
Edwin Smith dd07cea03d Remove the use->def chasing in cgSpillStack
We have a simplifier rule that does this now, and we want
CodeGenerator to work without relying on SSA form.
This also fixes a Str->Strb bug in ARM.

Reviewed By: @swtaarrs

Differential Revision: D1007836
2013-10-14 12:22:03 -07:00
Gordon Huang 61b9b59ee1 Add ArrayInit based functions in VariantController.h
ArrayInit based reservemap, add, and createmap is more efficient. Add them
to VariantController.h for extensions.

Reviewed By: andrii

Differential Revision: D1007534
2013-10-14 12:21:59 -07:00
Sara Golemon d6275160c4 Documentation driven skeleton generator
Parses svn.php.net's docbook sources for an extension's API
and generates a Systemlib and Extension source file for it.

Reviewed By: @ptarjan

Differential Revision: D989163
2013-10-14 12:21:55 -07:00
Eugene Letuchy 94de7e64ae add test of direct array invocation to .cuf.php quicktest
Depends on D984939. Instead of copying the entire test,
 ensures that in each case with an array() callable is followed
 immediately by a direct call(). To start with, cases that cause
 fatals are commented out. I also renamed "foo" and "bar" to
 "meth" and "staticMeth", for readability.

Reviewed By: @jdelong

Differential Revision: D1002897
2013-10-14 12:20:45 -07:00
David Gomez Cermeno 148aaef437 Fixing python serialization. Part one.
The first step is to merge SerializationPythonVariant and
UnserializationPythonVariant into PythonVariant. Even when the Variant
handles two different sets of types (Variant = object for unserialization
and Variant = PyObject* for serialization), FBSerializer was modified to
use templates instead of accessing types definitions in the Variant, so the
types defined in the PythonVariant are only used by Unserialization.

Next:
Specify a MutableStringType in the Variants (StringType in
old SerializerController is not necessarily equals to StringType in
VariantController).
Add PythonVariant as a trait.

Reviewed By: andrii

Differential Revision: D1003710
2013-10-14 12:20:41 -07:00
Abel Nieto 951f7e10d0 Implement equality operator.
Abstract away the code for equality from Vector to BaseVector, so we can reuse it
in FrozenVector.

Reviewed By: @dariorussi

Differential Revision: D1006830
2013-10-14 12:20:37 -07:00
Vaishaal Shankar 6d10c5a0f9 Clean up, optional initialization, logging to disk
Miscellaneous cleanup, including:
- Only initializing the profile data structure if requested
- Save the profile to disk with some frequency
- Move internal functions out of the header

Reviewed By: @jdelong

Differential Revision: D921078
2013-10-14 12:19:36 -07:00
seanc 945db1173d Fix GCC 4.8 warning spew
Summary: Suppress unused local typedef warning in GCC 4.8 because it is
currently triggered by multiple Boost (at least as of 1.53) headers.

Reviewed By: @sgolemon
2013-10-14 11:26:33 -07:00
Sara Golemon bad8a99b4a Support dynamically loadable extensions
Build an SO then load it with:

config.hdf
  DynamicExtensionPath = /usr/local/hhvm/lib
  DynamicExtensions {
    * = calendar.so
    * = runkit.so
    * = mhash.so
  }

Reviewed By: @jdelong

Differential Revision: D976840
2013-10-11 16:47:55 -07:00
Sara Golemon 73085a3043 Support loading mini-systemlibs from extensions.
Create a registry for per-extension systemlibs to be
loaded from the binary and parsed at InitModules() time.

Auto-embed runtime/ext/ext_foo.php as systemlib.ext.foo

loadSystemlib() looks for systemlib.ext.foo and calls
CompileSystemlib() which parses the section and merges
immediately as well as storing for later re-merging (if needed).

Enables the following <<__Native>> pattern:
  virtual void moduleInit() {
    HHVM_FE(myfunc);
    loadSystemlib();
  }

Where the extension systemlib has a declaration for myfunc().

Reviewed By: @jdelong

Differential Revision: D986853
2013-10-11 16:47:55 -07:00
mwilliams 6bcc04dc14 SharedString should use AtomicSharedPtr
Right now, SharedPtr works, because SharedStringData provides
atomic ref counting. But I need to make some changes to SharedPtr which
break it. Use AtomicSharedPtr instead (this is what AtomicSharedPtr is
for).

Reviewed By: @dariorussi

Differential Revision: D1006407
2013-10-11 16:47:54 -07:00
bsimmers 05b7047748 Clean up FrameState's block handling
This is some reorganization I did to use FrameState in guard
relaxation. It cleans up the interface used to enter and exit blocks by using
startBlock and finishBlock instead of the old methods.

Reviewed By: bertrand

Differential Revision: D1005829
2013-10-11 16:47:54 -07:00
bsimmers 5f8e5f97c6 Fix catch trace bug and inline cost bug
The catch trace map was being updated as we went along, instead of at
the end of translation along with all the other metadata. shouldIRInline was
treating the immediate vector for Switch and SSwitch as an m-vector.

Reviewed By: @ottoni

Differential Revision: D1005823
2013-10-11 16:47:54 -07:00
javer e9dcad8710 Add file_uploads and upload_tmp_dir to ini_get
Add file_uploads and upload_tmp_dir to ini_get options

Closes #1158

Reviewed By: @JoelMarcey

Differential Revision: D1007352

Pulled By: @scannell
2013-10-11 16:47:54 -07:00
Jordan DeLong 277cdda2ea Add a unit test for type inference
Courtesy of erling.

Reviewed By: @swtaarrs

Differential Revision: D1005514
2013-10-11 16:47:53 -07:00
Jordan DeLong 2f21d4d3a1 Support already-sorted EHTabs in FuncEmitter.
Because we re-sort the EHEnt table every time we load from
the repo, it's impossible to represent certain configurations of
fault/catch regions that are not made illegal in the spec.  For
example, you can't have a Fault and Catch region with the same extents
where the Fault region should be considered "outer" to the Catch
region.  This changes things to serialize parentIndexes to the repo,
and adds support to the FuncEmitter to tell it not to re-sort the
EHTab if a given user knows they've sorted it properly (and set up
parentIndexes) already.  Also adds some assertions about the required
sorted properties.

Reviewed By: @dariorussi

Differential Revision: D1002108
2013-10-11 16:47:53 -07:00
Weijing Liu 2b3cb70917 added "Attempted to interpret unknown debugger command as PHP" into the error message
The error message for a bad command is misleading. Added "Attempted to interpret unknown debugger command as PHP" into the error message

Reviewed By: @mikemag

Differential Revision: D989538
2013-10-11 16:47:49 -07:00
Sara Golemon 59e5f4f7a7 Revert "Get ARM disassembly printing in printir:2"
This reverts commit 23745b0488.

It's templates all the way down
2013-10-11 16:02:35 -07:00
Sara Golemon cfe532c435 Increase maximum template depth 2013-10-11 15:39:13 -07:00
Sara Golemon b28ad00067 Suppress gcc4.8 warning from double-conversion
double-conversion uses this typedef as a sort
of a static assert for the template.

Mark it as explicitly unused so we don't get
a warning.
2013-10-11 12:22:07 -07:00
Bert Maher f4b56502d5 Test case for reflowTypes with hottrace PGO
Thought it would be good to check this in since it was useful
in diagnosing a sandbox bug.

Reviewed By: @ottoni

Differential Revision: D1007313
2013-10-11 10:41:15 -07:00
mwilliams 3871d1c37f Don't interpOne nopped out BoxRs
BoxR is always interpOned. If its nopped out, we should skip it.

Reviewed By: @ottoni

Differential Revision: D1006405
2013-10-11 10:41:11 -07:00
Paul Tarjan 007f191202 make debugger work with old editline
These functions are stubs in editline anyways, so in order to support Ubuntu 10.04 using editline 2.11-20080614-1build1 just ifdef them out

Reviewed By: @sgolemon

Differential Revision: D1006813
2013-10-11 10:41:07 -07:00
Bert Maher 733efe3201 Moving a few more helpers to translator-runtime
Found these while poking around tx64...

Reviewed By: @swtaarrs

Differential Revision: D1006852
2013-10-11 10:41:03 -07:00
bsimmers 874170c8a2 Fix the tracelet region selector to correctly end a trace
There were a few situations where the bcOff used in the ReqBindJmp at
the end of the trace was either for the wrong function or the wrong instruction
in the correct function. We can now explicitly pass it into HhbcTranslator::end
to make sure it's correct all the time.

Reviewed By: @bertmaher

Differential Revision: D1005831
2013-10-11 10:40:59 -07:00
Joel Marcey 167fb38291 Add PHPUnit to list of framework tests and make a few other changes.
Wanted to add PHPUnit to our list of frameworks to test. While doing so, I made a few extra changes such as making the hhvm build be in JIT mode. And re-ran the tests again to get a new baseline and summary file.

(Ignorning conflict markers because symfony uses 7+ = signs in some of their tests, which causes conflict marker errors here: diffusion/E/browse/admin/scripts/git/hosting/hooks/update.d/430.conflict_markers.sh)

@EntNotFoundException

Reviewed By: @ptarjan

Differential Revision: D1006290
2013-10-11 10:40:55 -07:00
Owen Yamauchi 23745b0488 Get ARM disassembly printing in printir:2
I'm getting to the point where it's helpful to see the ARM code being
emitted, and this is the most natural way to hook it up.

There's a little wrinkle here in that sometimes (e.g. smashable jumps),
there's stuff in the TC that isn't executable code. In this case the
disassembly is either "Unallocated" or some nonsense instruction. We
could avoid this with sufficient metadata, but I'm not convinced it's
necessary yet. (FYI, this pattern -- data embedded in code -- is common
in ARM code, to judge by the vixl assembler's inclusion of an
abstraction to do this very thing.)

In the process I had to convert vixl's printing facilities to use
std::ostream instead of FILE*. I converted it to use folly::format
instead of fprintf as part of this.

Also added an --arm flag to hhvm_wrapper.php to make my life easier.

Reviewed By: @edwinsmith

Differential Revision: D1006435
2013-10-11 10:33:16 -07:00
bsimmers 447818d288 Assert instruction input flavors before translating
We don't have a translation for Box, so we always interpOne it and all
of its inputs are marked dontGuard. If the input to the Box was produced in a
previous tracelet, this means we won't know its type in the jit, and it was
upsetting the code figuring out the output type of the interpOne. We know from
the bytecode that the input is always a Cell, so assert that before translating
the instruction.

Reviewed By: @ptarjan

Differential Revision: D1006328
2013-10-11 10:33:08 -07:00
bsimmers 306648236e Reenable FCall type prediction in opt builds, fix KindOfRef predictions
This was (we think) accidentally disabled in non-debug builds a long
time ago, and some type shuffling I did a while ago broke KindOfRef
predictions. RuntimeType expects an inner type of KindOfAny instead of
KindOfNone.

Reviewed By: @kmafb

Differential Revision: D1004691
2013-10-11 10:33:04 -07:00
bsimmers 98237ae3e0 Split EndCatch into TryEndCatch and EndCatch
EndCatch was supposed to be terminal in some catch traces but not in
other. We know which is which at compile time, so now we use TryEndCatch for
the non-terminal case and EndCatch for the terminal case.

Reviewed By: @edwinsmith

Differential Revision: D1005802
2013-10-11 10:32:14 -07:00
Edwin Smith 43ac592c3a Change the block labels in prettyprint output to B instead of L.
Reviewed By: @ottoni

Differential Revision: D1005392
2013-10-10 18:07:23 -07:00
Kristaps Kaupe deaa96b882 Fix macro typo in native.h
Fix macro typo in native.h

Reviewed By: @JoelMarcey

Differential Revision: D1005290

Pulled By: @scannell
2013-10-10 18:07:23 -07:00
Paul Tarjan 5015c7f1aa Implement PharData::extractTo
This is needed for composer to install the dependancies for phpunit.

I also upgraded composer while I was in there.

Reviewed By: @JoelMarcey

Differential Revision: D1005174
2013-10-10 18:05:53 -07:00
Abel Nieto b9c50323f6 Make FrozenVector a collection
Add FrozenVector as a collection.

Enable the following:
  * frozen vector literals
  * casting fvs to array and bool
  * array_key_exists and isset with fv

Reviewed By: @paroski

Differential Revision: D988612
2013-10-10 18:02:39 -07:00
Alex Malyshev 833811804f Implement date_parse_from_format
Ended up doing a little of refactoring around DateTime too.

This is for a fatal in Laravel.

Reviewed By: @JoelMarcey

Differential Revision: D995643
2013-10-10 18:02:38 -07:00
Herman Venter 981c4e3d21 Use a separate field to keep track of allocations for the purpose of out of memory checking.
When jemalloc is used, the code for tracking out of memory situations conflicts with the code that figures out how much memory is actually in use. To solve this, I've introduced a new usage counter field in the memory manager. Presumably, this counter is less accurate than the one that is maintained by the jemalloc specific code in MemoryManager::refreshStatsImpl, but this should not matter because it's only role is to trigger an out of memory check, which is done using the usage field maintained by refreshStatsImpl. If this check is triggered, the new counter is updated to the presumably more accurate value.

Reviewed By: @edwinsmith

Differential Revision: D994503
2013-10-10 18:02:38 -07:00
javer 76bb596eaf Fix nested include files class context propagation
Fix nested include files losing class context

Closes #1009
Closes #1149

Reviewed By: @markw65

Differential Revision: D1004416

Pulled By: @scannell
2013-10-10 10:32:19 -07:00
Guilherme Ottoni aaa79a9a48 Fix some uses of JitPGO runtime option
We were incorrectly checking if JitPGO was enabled to skip some things
that are only intended to be skipped during profiling translations.
This was resulting in worse code to be generated in TransLive mode.

Reviewed By: @swtaarrs

Differential Revision: D1004077
2013-10-10 10:32:19 -07:00
Brett Simmers cf38b4f72c Add some type-related asserts
These will catch some bugs a littler earlier

Reviewed By: @jdelong

Differential Revision: D999631
2013-10-10 10:32:17 -07:00
Chad Horohoe 02cfa05d19 Remove notices on mysql query failures
Zend only has this sort of behavior when mysql.trace_mode is
enabled, but it's off by default. Since the mysql library is deprecated
and people should be using mysqli, it makes sense to emulate mysqli's
behavior here and not warn at all rather than trying to implement
mysql.trace_mode.

Closes #1140

Reviewed By: @markw65

Differential Revision: D1000998

Pulled By: @scannell
2013-10-10 10:32:17 -07:00
Eugene Letuchy bc1642581a make ()-invoke and call_user_func a bit more uniform ...
A `$var` containing a string, a closure, and (by
 happenstance?) functor instance, worked when invoked directly by a
 pair of parens afterwards. This diff extends that behavior to also
 support the ##array($instance, 'method')## and ##array('Class',
 'method')## callable syntaxes.

 It would be nice if we had a facility for
 explicitly creating function pointers in the runtime.

Reviewed By: @jdelong

Differential Revision: D984939
2013-10-09 16:30:09 -07:00
Sara Golemon ca05e23280 Add a few new functions to variantcontroller api
Helpers for dealing with static strings and empty arrays.

Reviewed By: andrii

Differential Revision: D1003287
2013-10-09 16:30:04 -07:00
Owen Yamauchi 0ad0b0ddfd ARM implementations of a few more IR opcodes
I ran test/quick and found a whole bunch of failures due to repeated
codegen failure, meaning there are some IR opcodes that have to appear
even when everything is interp-one'd. This implements a few of those.

This entailed implementing a few core bits of infrastructure, including
smashable jumps, which you can read all about in jump-smash.cpp. I came
to this approach because the jump offsets that ARM allows are too small
for our purposes. The fact that this skirts around the delicate parts of
concurrent modification and execution is a side benefit.

I'm putting off the implementation of GuardRefs for this diff because
it's very complex and I want to investigate factoring out shared logic.
But I stopped it from punting in codegen just so execution would get a
bit further.

Reviewed By: @ottoni

Differential Revision: D1002619
2013-10-09 13:47:25 -07:00
Chad Horohoe 979a5dc3ae Add several missing MYSQLI_ constants
All values current as of PHP 5.5.4.

I also found two other constants on php.net (MYSQLI_CLIENT_MULTI_QUERIES
& MYSQLI_NEED_DATA), but outside of that mention I can't find them...
they're not in the 5.5.4 or master source, and I can't find any
supporting documentation for them (or that they've been
deprecated/removed).

Closes #1144

Reviewed By: @JoelMarcey

Differential Revision: D1003188

Pulled By: @scannell
2013-10-09 13:47:25 -07:00
Tymoteusz Motylewski 4a1445b9d3 Add missing constant PHP_MAXPATHLEN
Adds missing constant PHP_MAXPATHLEN

Closes #1143
Closes #1145

Reviewed By: @JoelMarcey

Differential Revision: D1003269

Pulled By: @scannell
2013-10-09 13:47:25 -07:00
Sean Cannella 386ed2d3ee Fix xmlwriter_open_uri signature
xmlwriter_open_uri should return a Variant, not an Object (it
can return bool(false) which fixes some Zend tests.)

Reviewed By: @JoelMarcey

Differential Revision: D1003258
2013-10-09 13:47:25 -07:00
Guilherme Ottoni 085409c943 Increase spill area
From 32 to 64 cells.

Reviewed By: @edwinsmith

Differential Revision: D991291
2013-10-09 13:47:24 -07:00
Brett Simmers 7a7820b2e8 Use the correct closure class name in the emitter
There were locals named clsName and className in this function, and
the call to setClosureClassName was using the wrong one. This could create two
classes with the same name: one in the file defining a trait with a closure and
any file with a class that uses the trait.

Reviewed By: @markw65

Differential Revision: D1002162
2013-10-09 13:47:24 -07:00
Guilherme Ottoni 1831228ac9 Get test/slow/ext_datetime/strtotime_leak.php working with PGO
This test was reporting a memory leak with PGO because a retranslation
was triggered between consecutive calls to memory_get_usage().  So
bump the PGO threshold for this test to avoid the problem.

Reviewed By: @bertmaher

Differential Revision: D1001851
2013-10-09 13:47:24 -07:00
Abel Nieto 8131a35818 Add a FrozenVector extension class
FrozenVector is a Vector with immutable entries. Specifically, it implements the ConstVector interface.

Abstract the functionality common to both Vector and FrozenVector in a BaseVector class.

TODO:

  * enable literal syntax.
  * make FrozenVector play nicely with var_dump
  * make FrozenVector a collection.

Reviewed By: @paroski

Differential Revision: D986967
2013-10-09 13:47:23 -07:00
mwilliams 1891b7eb08 Fix type prediction for constants in the region translator
Predicted types for constants came from analyze, and
were thrown away before we got to the region translator.
Move the predictions to the same routine that does the rest
of them.

Reviewed By: @swtaarrs

Differential Revision: D1001083
2013-10-09 13:47:23 -07:00
Jordan DeLong 467c44f494 Remove bytecode invariant about fault funclet uniqueness
We used to need this because when executing an Unwind
instruction we tried to find a PC to re-raise the fault at based on
the offset of the fault funclet.  This didn't quite work (adjacent
fault regions weren't handled correctly), and was changed in D697005,
so I think we can drop this requirement now.

Reviewed By: @edwinsmith

Differential Revision: D1000915
2013-10-09 13:47:23 -07:00
Owen Yamauchi 358ffe154c Refactor smashable-jump code
Parts of the runtime other than codegen need to be able to read, write,
and smash jumps. I pulled this logic into its own module, jump-smash,
which hides platform-specific implementations behind a platform-agnostic
interface. This entailed a bunch of other Asm->CodeBlock changes too.

I can't be sure that I've found all the places where smashable jumps are
written -- we may have some places where it's just open-coded -- but we
can clean those up as we find them.

Reviewed By: @jdelong

Differential Revision: D997737
2013-10-09 13:47:22 -07:00
mwilliams a58943c191 Fix catch traces for mod
Each catch trace needs exactly one predecessor,
so they can't be shared.

Reviewed By: @edwinsmith

Differential Revision: D999095
2013-10-09 13:47:22 -07:00
Bert Maher cbafa20f16 Use std::atomic instead of google_base for shared counters
Gets rid of the dependency on google_base for atomic
increment.  Works around the fact that AHM values must be copy
constructible (and std::atomics aren't) by creating a wrapper class
with non-atomic copy construction to hold counters.

Reviewed By: @jdelong

Differential Revision: D1000766
2013-10-09 13:47:12 -07:00
javer 289fea08a4 Fix gmdate timezone
Fix gmdate timezone

Closes #1139
Closes #1142

Reviewed By: @JoelMarcey

Differential Revision: D1000995

Pulled By: @scannell
2013-10-09 13:23:20 -07:00
Joel Marcey e39274a817 Update README.md 2013-10-08 18:24:03 -07:00
Joel Marcey ed9498e66e Update README.md 2013-10-08 17:53:39 -07:00
Joel Marcey 06efef7c10 Update README.md 2013-10-08 17:53:17 -07:00
Joel Marcey 147bc162c5 Update README.md
grammar
2013-10-08 16:33:38 -07:00
Joel Marcey ff41f28f1c Update README.md
Add information about our updated FAQ.
2013-10-08 16:33:04 -07:00
Joel Marcey 2034d9be5e Update README.md 2013-10-08 15:37:24 -07:00
Sara Golemon 1df9eec73c Detect libedit and use it if readline not available 2013-10-08 09:33:55 -07:00
mwilliams 665941d2fe Fix races in bind* service requests
bindJmpccFirst is not idempotent. If two requests are running
through the service request at the same time, with opposite
conditions, we're extremely likely to generate incorrect code.

The rest are more-or-less idempotent, but since they have
reusable stubs they need to check whether its already run,
in order to avoid releasing the stub multiple times.

Finally, the bind* calls should avoid running more than
once because each time they call chainFrom, which adds another
IncomingBranch (harmless, but wasteful).

Reviewed By: @jdelong

Differential Revision: D997810
2013-10-08 09:18:09 -07:00
Edwin Smith 07bbaa729b Change insertAsserts to iterate over the control flow graph
Instead of using traces.

Reviewed By: @jdelong

Differential Revision: D987651
2013-10-08 09:18:09 -07:00
Edwin Smith df6f76234a Save scratch registers in cgGenericRetDecRefs()
And, clean up the stackAdjust code by using PhysRegSaverStub.
The stub code ended with RET 8, but that wasn't actually
necessary and was requiring the JIT code to adjust for it.
Just end with RET, which keeps RSP evenly balanced.

Reviewed By: @jdelong

Differential Revision: D999380
2013-10-08 09:18:09 -07:00
Jordan DeLong c3ff82fd71 Remove lookupKnownClass<true> (dead code)
We only use the false case now.

Reviewed By: @markw65

Differential Revision: D997502
2013-10-08 09:18:08 -07:00
Jordan DeLong ae11c0a584 Tweaks to RDS changes
Fix indentation of detail namespace and log strerror(errno)
if madvise fails.  Add a constant for 16-byte alignment.

Reviewed By: @swtaarrs

Differential Revision: D997449
2013-10-08 09:18:08 -07:00
Jordan DeLong c5186329e0 Clean up some classIsPersistent functions
I think the one in hhbc-translator.cpp might be a bug.

Reviewed By: @markw65

Differential Revision: D990844
2013-10-08 09:18:08 -07:00
Jordan DeLong 42ca6d5ebd Clean up target cache
Just delete some unused stuff, simplify the Cache<> template
a lot.  Delete some vestigial things in MethodCache (the Pair,
keyToPair function, etc).  That's all I'm going to do here for now.

Reviewed By: @markw65

Differential Revision: D990840
2013-10-08 09:18:08 -07:00
Jordan DeLong cee077faee Clean up RDS / target cache, part 3
Move the target caches back to JIT::, since they are now
mostly a JIT specific use case of RDS.  Some target cache cleanup on
top in separate diff.

Reviewed By: @markw65

Differential Revision: D990837
2013-10-08 09:18:07 -07:00
Jordan DeLong 68d297d007 Clean up RDS, part 2
Part two tries to sort out the different types of allocations
from RDS, and abstract the allocation pattern found in a few runtime
structures into an RDS::Link type, and simplify namedAlloc stuff (most
namespaces were dead, and it also did unnamed allocs).  This also
allowed moving the unwind-specific parts of the header into a
dynamically-bound RDS::Link.  (Which also reduced header dependencies
for this module.)

The comments in the header hopefully make the idea clear.  A part 3 is
still coming, in which I plan to move the remaining actual "target
caches" back to JIT::, as just a use case of RDS.  The rds.h itself is
still going to be a central place where different "symbol" types have
to be registered, but I think that is probably ok and still a bit more
modular than it was.  (Ideally the symbols would have types associated
with them, but this would make rds.h depend on the JIT cyclically,
which is unfortunate, so I figure having helper functions for
different symbols that force the type is a reasonable enough thing.)

Reviewed By: @swtaarrs

Differential Revision: D990590
2013-10-08 09:18:07 -07:00
Drew Paroski 7ee2c02123 Add toValuesArray() and toKeysArray() to various traits/interfaces
This diff adds declarations and implementations as needed to make
toValuesArray() and toKeysArray() part of Iterables and KeyedIterables
respectively.

Reviewed By: @elgenie

Differential Revision: D998700
2013-10-08 09:18:06 -07:00
Drew Paroski ed5e22c3c8 Fix bug with how HphpArray::CopyReserve() initializes m_pos
For non-packed HphpArrays, CopyReserve() was blindly copying m_pos from the
source array to the new array. This is incorrect because tombstones are not
copied over to the new array. This diff adds appropriate logic to recompute
m_pos for the new array.

Reviewed By: @jdelong

Differential Revision: D998944
2013-10-08 09:18:06 -07:00
Jordan DeLong 63aa756249 Pull UserAttributeMap typedef out of Class/Func
I want to use it outside of these guys for now.  Also make
hphp-value.h #include'able without pulling all of complex-types.h

Reviewed By: @markw65

Differential Revision: D998305
2013-10-08 09:18:06 -07:00
Jordan DeLong 275e314941 Print fpi entries in func pretty print
I've added this a few times for local debugging and never
committed it.  It's kinda useful.

Reviewed By: @bertmaher

Differential Revision: D1000633
2013-10-08 09:18:06 -07:00
Jordan DeLong 2259e996ee Move HPHP::MD5 to util/
And split the small portion of util/util.h that it needed to
its own header.

Reviewed By: @andralex

Differential Revision: D996208
2013-10-08 09:18:05 -07:00
Jordan DeLong 2c54e73091 Fix MD5::toString memory leak, other cleanup
Also broke dependency on zend_string to move it to util
(separate diff).

Reviewed By: @andralex

Differential Revision: D996205
2013-10-08 09:18:05 -07:00
Jordan DeLong 2a18049e00 Don't store smart allocated Strings in FunctionScope
These are populated from various worker threads during
compilation (in the FunctionScope::setParamSpecs code path they aren't
static strings), and it was hitting the checkPreFree assertions that
smart-freed memory came from the allocator it was being free'd to.

Reviewed By: @markw65

Differential Revision: D1000408
2013-10-08 09:18:04 -07:00
bsimmers 2f31a744e6 Pull TraceBuilder's state-tracking bits out into FrameState
TraceBuilder is now only responsible for creating, optimizing, and
appending instructions, as well as high-level control flow
operations. updateTrackedState and all related methods and fields now live in
FrameState. This will let us use it in modules other than TraceBuilder where
the information it provides would be valuable.

Reviewed By: @edwinsmith

Differential Revision: D998255
2013-10-08 09:18:04 -07:00
bsimmers 9c9977c05a Stop using Type::None for unknown locals or stack slots
We were only doing this for historical reasons and it was needlessly
complicating the code.

Reviewed By: @jdelong

Differential Revision: D996549
2013-10-08 09:18:03 -07:00
Bert Maher 781854cc33 Clear out convObjToBoolHelper
Another trivial helper bites the dust

Reviewed By: @ottoni

Differential Revision: D999834
2013-10-08 09:18:03 -07:00
bsimmers a670b3fb24 Disable some broken tests
Reviewed By: @alexmalyshev

Differential Revision: D1000016
2013-10-08 09:18:02 -07:00
Mike Magruder 89fd801c58 Enable support for libedit in hphpd
Make hphpd compatible with both readline and libedit. Also fixes an issue with ctrl-c out of reverse history search. While searching, ctrl-c will now erase the current search result. Pressing enter will drop out of the search, but with the last match now presented on the hphpd command line. Ctrl-c again will erase the current command (as per usual) and leave a clean slate. Ideally, one ctrl-c during search would drop out of the search, but I've not found a way to get readline to do that for me. At least you can get out of history search without executing a command now, which is a big improvement.

Reviewed By: @scannell

Differential Revision: D993558
2013-10-08 09:18:02 -07:00
mwilliams 0b785af6a7 Prevent hang when numa isn't available
next_numa_node needed to check that its enabled.

Reviewed By: @edwinsmith

Differential Revision: D999329
2013-10-08 09:18:01 -07:00
Sara Golemon af3192aab1 Link numa into hphp_util rather than hphp_runtime_static
Closes #1141
2013-10-08 09:12:11 -07:00
Sara Golemon e27c855d02 no.cpp files don't exist anymore 2013-10-07 14:04:36 -07:00
Sara Golemon e2bd6d6769 Make hphp/util its own static lib 2013-10-07 14:04:32 -07:00
Sara Golemon 78400882be Make hphp/zend its own static lib 2013-10-07 14:03:41 -07:00
Sara Golemon 2f84ffa0fd Make hphp/parser its own static lib 2013-10-07 13:35:09 -07:00
Eugene Letuchy b02db7a200 Merge pull request #1138 from elgenie/master
Add CONTRIBUTING.md
2013-10-07 12:02:29 -07:00
Eugene Letuchy bc97f9a704 Add CONTRIBUTING.md
Per https://github.com/blog/1184-contributing-guidelines, adding this
file will add a link at the top of issues and pull requests.
2013-10-07 11:59:20 -07:00
Sean Cannella bf85e19b51 Update README.md
Fix typos
2013-10-07 11:56:19 -07:00
Edwin Smith 2be3c3af35 Don't access uninitialized postorder ids in findDominator().
If a block isn't reachable, it will not be assigned a postorder
id in rpoSortBlocks().  The dominator algorithm incorrectly
used unreachable blocks postorder ids, which could lead to general
badness including crashes or miscompilations

Reviewed By: @jdelong

Differential Revision: D998809
2013-10-07 08:40:45 -07:00
Andrii Grynenko f395aad3f1 Extend FBUnserializer API to allow it to be used by other algorithm
Allow FBUnserializer to be used as a building block for other algorithms using fb_serialization.

Reviewed By: zhuohuang

Differential Revision: D996689
2013-10-07 08:40:45 -07:00
Sean Cannella 6b97716bc9 ASAN build fixes for vixl
Never tried the vixl tests under ASAN before, this fixes a couple bugs.

Reviewed By: @edwinsmith

Differential Revision: D998518
2013-10-07 08:40:44 -07:00
Jordan DeLong 17cb7b0c38 Remove FixedFuncCache, refactor LdFuncCache* instructions
FixedFuncCache was just one helper function which called
autoload.  The translations used offsetofs on FixedFuncCache even
though they were using allocFixedFunction to get the Handle now.  Move
the runtime helper out of the RDS namespace since it really didn't do
anything with RDS stuff (just calls loadFunc).  Changed LdFuncCached*
implementations to use extra-data.  Also I opted it back out of
native-calls, since it seems initially confusing to learn that it did
more than just a native call, and a cgCallHelper seemed clearer when
it does more than just a call: no need to go look up what it calls in
the other .cpp.

Reviewed By: @bertmaher

Differential Revision: D989157
2013-10-07 08:40:44 -07:00
Jordan DeLong 5d4da49c9a Remove various dead code relating to fb_rename_function
Apparently there used to be an API to limit the renamable
functions to a particular set, but this no longer exists.  Delete code
related to it.

Reviewed By: @bertmaher

Differential Revision: D989168
2013-10-07 08:40:44 -07:00
Jordan DeLong 01f45dc835 Cleaning up RDS, part 1
This is a quick start of cleaning up and documenting the RDS
(formerly target cache) module.  This diff contains:

  - a few renames to make things reasonable wrt the containing namespace

  - make Class::wouldCall a non-member function

  - various additional renames of "target cache" to "RDP"

  - the start of some documentation about what it is

Reviewed By: @markw65

Differential Revision: D989135
2013-10-07 08:40:43 -07:00
Jordan DeLong 26669ccca8 Move runtime/vm/jit/target-cache.h to runtime/base/rds.h
Separate diff for rebase-ability and reviewability.

Reviewed By: @edwinsmith

Differential Revision: D989134
2013-10-07 08:40:43 -07:00
Jordan DeLong 6bfe5f011d Rename TargetCache:: to RDS::
In its own diff for reviewability.

Reviewed By: @edwinsmith

Differential Revision: D989132
2013-10-07 08:40:42 -07:00
Jordan DeLong c33c69ee24 Move TargetCache out of Transl:: and rm using directives of TargetCache
If we want to keep the namespace, we should make the naming
such that using directives aren't needed.  (Follow up diffs will make
the naming reasonable.)

Reviewed By: @edwinsmith

Differential Revision: D989131
2013-10-07 08:40:42 -07:00
Sara Golemon 26347b06ef Make neo its own static lib 2013-10-04 22:59:35 -07:00
Drew Paroski cd495c072b Add values() method to collections, StrictIterable, LazyIterable, etc.
All keyed collections (and KeyedIterables in general) have a keys() method,
but only Map and StableMap have a values() method. This diff adds values()
to all collections and the relevant traits and helper classes.

Reviewed By: @elgenie

Differential Revision: D990602
2013-10-04 18:26:10 -07:00
Bert Maher 3ed6afdf07 Use a global litstr table in RepoAuthoritative/WholeProgram mode
When we're building a repo in WholeProgram mode, create a
single unified Litstr table for all static strings that we encounter
in all units, and use this table when running in RepoAuthoritative
mode.  This appears to save ~100MB of repo compared to the previous
method that stores strings for each unit separately in the UnitLitstr
table, since we had a lot of duplication.

Still use the UnitLitstr if we're not doing WholeProgram/RepoAuth,
because multiple processes attempting to use the same repo can try to
write the same string with different IDs, and that causes all sorts of
problems.  We could maybe deal with that by getting the database
involved when try to get a litstr ID, but that seems more complicated
than it's worth.

Reviewed By: @markw65

Differential Revision: D985326
2013-10-04 18:26:09 -07:00
mwilliams b51446c3af Side exits are conditional
so its best not to smash them with unconditional jmps

Reviewed By: @jdelong

Differential Revision: D997385
2013-10-04 18:26:08 -07:00
Bert Maher 62e39079be Remove box_value wrapper function, call RefData::Make directly
To do this I changed RefData::Make to take a TV.  I like the
result, but feel free to disagree and I'll change it back.

Reviewed By: @jdelong

Differential Revision: D992097
2013-10-04 18:26:08 -07:00
Bert Maher c2a64b4840 Add pgo shortcut to test/run
So I don't have to remember options

Reviewed By: @ottoni

Differential Revision: D996775
2013-10-04 18:26:08 -07:00
bsimmers ba02df1b2d Don't let a pointer to a local escape its scope
This code was written before tvScratch existed, and this is exactly
what tvScratch is intended for.

Reviewed By: @markw65

Differential Revision: D995591
2013-10-04 18:26:07 -07:00
Paul Tarjan 367711fbeb stop populating TRACK_VARS_REQUEST
There is no code in php-src that relies on this, and the variable that holds it doesn't even have space for a 7th entry.

Reviewed By: @scannell

Differential Revision: D997179
2013-10-04 18:26:07 -07:00
Joel Marcey 1312f577cf Change git hash for phpbb3. Check for git hash changes in the code. Allow the forced regeneration of expect files.
The phpBB folks fixed their tests as a result of some of our findings. This precipitated a change in the git has we were using to download the source code. Also, this required us to check whether a git hash has changed and, if so, redownload the entire framework. Also added a capability to force a regeneration of an expected results for for a given framework. This could be useful after a redownload or other occasions.

Thanks @alexmalyshev for the heads up re: the phpBB source change.

Reviewed By: @ptarjan

Differential Revision: D996779
2013-10-04 18:26:06 -07:00
Owen Yamauchi ffc5874366 Replace some EvalSimulateARM checks
Once we start trying to run on ARM hardware, we'll need to start doing
some stuff differently. The idea here is to separate the questions "are
we emitting ARM code?" and "are we running the ARM simulator?".

Not all checks of the flag are gone; in particular, the stuff that reads
the simulator's stack pointer, and that sets it up in enterTC, should
actually be checking if we're simulating.

I'm open to suggestions on naming; I just wanted something terse.

Reviewed By: @jdelong

Differential Revision: D995817
2013-10-04 18:26:06 -07:00
Owen Yamauchi eab06d7bf9 Move emitFallbackJmp stuff out of TranslatorX64
This is starting to broach the thorny issue of what we do about all the
jump emitting and smashing machinery in the SrcDB family. I think I'll
end up factoring out all that logic into its own module which knows how
to emit and smash jumps on all platforms.

Reviewed By: @jdelong

Differential Revision: D995736
2013-10-04 18:26:06 -07:00
Weijing Liu 1732743f58 * is added to indicate the current line of code
insert a start to indicate the current line of code if colorization is off.

Reviewed By: @mikemag

Differential Revision: D983975
2013-10-04 18:26:05 -07:00
Bert Maher 13dbeee63c Make the region compiler more conservative when doing inline decrefs at RetC
The region compiler was counting Type::None as an "uncounted"
type when deciding whether it should emit an inline sequence of
decrefs at the end of a function vs. calling a helper.  In
cache_get_scb, this leads to a sequence of 52 DecRefLoc's in a row,
which just can't be good for icache.

Reviewed By: @edwinsmith

Differential Revision: D994936
2013-10-04 18:26:05 -07:00
Sean Cannella 5e0cd6a795 fix VIXL compilation on non-Linux
s/isnan/std::isnan/g

Reviewed By: @sgolemon

Differential Revision: D996133
2013-10-03 16:38:31 -07:00
Joel Marcey 1eb3cddaf7 Make OSS Test Script a real test runner - at least human runnable
A bit of a redesign and better user-experience.

This script runs one or more open source (oss) framework unit tests via PHPUnit. Run one or multiple tests by explicitly naming them at thecommand line, or specify --all to run all available tests. You will see various forms of output. The first time running a test suite for a framework, gray dots will appear to set the baseline for future runs. On subsequent runs, you will see green dots for tests that have the same status as the previous run. If something changes, you will see a red F if a test went from pass to something else. You will see a green F if a test went from something else to pass. You will see a blue F if a test stayed in the failing range, but went from something like E to I or F to S.

The summary for a test show the overall pass percentage of the unit test suite, irrespective of previous runs. The output and diff files for a test suite will show what tests pass or fail, and have why they failed.

Example output: P2777440

Future: Add number of total tests to be run at beginning in a clean way; fbmakify the runner

Reviewed By: @ptarjan

Differential Revision: D991614
2013-10-03 16:38:30 -07:00
bsimmers 8c14d6ebfb Kill TraceBuilder::m_refCountedMemValue
We don't completely trust it and it wasn't providing a measurable perf
win.

Reviewed By: @bertmaher

Differential Revision: D992711
2013-10-03 16:38:29 -07:00
Jordan DeLong b70c17766c Always-flat arrays for kMixedKind and kPackedKind
Reviewed By: @edwinsmith

Differential Revision: D988759
2013-10-03 13:33:57 -07:00
Jordan DeLong c0962c2651 Temporarily disable some oauth tests that use arrays
Reviewed By: @ptarjan

Differential Revision: D993555
2013-10-03 13:33:57 -07:00
bsimmers cd60431085 Disable a bunch of flaky tests
These all failed one or more times on contbuild in the past day.

Reviewed By: @scannell

Differential Revision: D995196
2013-10-03 13:33:57 -07:00
mwilliams 1cfc5ac9e3 Remove unused m_deps from SrcDB
Which gets rid of the last direct use of GrowableVector,
So move it inside GrowableVectorWrapper, and rename GrowableVectorWrapper
as GrowableVector.

Reviewed By: @edwinsmith

Differential Revision: D995169
2013-10-03 13:33:56 -07:00
mwilliams 23fa000262 Remove unused m_src from TranslArgs
It was set in a couple of places, but never read.

Reviewed By: @edwinsmith

Differential Revision: D995172
2013-10-03 13:33:56 -07:00
Sean Cannella b04c33d195 recursive mkdir tests need to be threadsafe
Use different directory names for recursive mkdir tests so they
can be run safely in parallel.

Reviewed By: @ptarjan

Differential Revision: D995116
2013-10-03 13:33:56 -07:00
Stephen Chen a1fad1ce2d add counter to hhvm that tracks how often pagelet queue overflows
add counter to hhvm that tracks how often pagelet queue overflows.

Reviewed By: bertrand

Differential Revision: D992624
2013-10-03 13:33:56 -07:00
Stephen Chen d47b333b78 Add counters for http response code in hhvm
Adds counters in the form of

http_response_200.rate.60
http_response_404.rate.60
http_response_500.rate.60

Reviewed By: bertrand

Differential Revision: D992473
2013-10-03 13:33:55 -07:00
Sean Cannella 16555d9b6d Fix intermittently failing file tests
File tests run in parallel should use independent paths to avoid creation/teardown interfering with each other

Reviewed By: @ptarjan

Differential Revision: D994417
2013-10-03 13:33:55 -07:00
Bert Maher 34fd2bfc63 Call iter->free directly from TC instead of through a helper
These guys were basically a fancy way of saying "jmp".

Reviewed By: @jdelong

Differential Revision: D993302
2013-10-03 13:33:55 -07:00
javer b02a6a8576 Implement SPL RecursiveRegexIterator
Implement SPL RecursiveRegex Iterator

Closes #1121

Reviewed By: @ptarjan

Differential Revision: D993915

Pulled By: @scannell
2013-10-03 13:33:54 -07:00
Jordan DeLong 448b3d2762 Make zero-arg hhbc macros for FOOMANY consistent wrt parenthesis
Some of them used them and some didn't.  Since NOV and NA
don't use them I went with no parens for anything taking zero args.

Reviewed By: bertrand

Differential Revision: D993735
2013-10-03 13:33:54 -07:00
Jordan DeLong 277373ba21 Remove a policy array string
Reviewed By: @edwinsmith

Differential Revision: D993523
2013-10-03 13:33:54 -07:00
Owen Yamauchi 05d1bf750f Get "hello world" running via interp-one in simulated ARM mode
It's for real this time. Sorry for the mega-diff, but this is all the
groundwork for simulated-ARM mode. This is the minimal amount of work I
had to do to get anything at all running.

I anticipate some requested changes on this diff, which I might
implement as updates, or as separate diffs that I then rebase this one
onto. But I would like to commit this diff once it's cleaned up.

Almost none of our tests pass in ARM mode yet, but I'd like to at least
get this out for review. I would like to commit without all the tests
passing -- I see that as a better alternative to going from zero to all
in a single diff, which would require an unmanageably large diff.

Next, I'll be working on getting all the tests to pass (by
implementing/fixing parts of the runtime infrastructure, not by
implementing real translation). Once they're all passing, we can set up
contbuilds, and then anyone who wants to can pitch in, implementing real
translation for more and more IR opcodes.

Reviewed By: @edwinsmith

Differential Revision: D979505
2013-10-03 13:33:53 -07:00
Sean Cannella 0c07027988 ASAN: Fix alloc/dealloc mismatch in hotprofiler
Fix mismatched new[] with delete in hotprofiler

Reviewed By: @mikemag

Differential Revision: D993550
2013-10-03 13:33:53 -07:00
Herman Venter 0b3d7e163c Give a compile time error if the value and/or key of a foreach statement is a function call.
Function calls do not have left hand values, so such statements are not legal and absent the compile time error, the code generator generates bad code resulting in an assert.

Reviewed By: @markw65

Differential Revision: D991883
2013-10-03 13:33:53 -07:00
Sara Golemon 24bf986c7e Build vixl as a separate module 2013-10-03 13:33:53 -07:00
Paul Tarjan 0fb8f622c6 import oauth extension (take 3)
Now that mark found the issue with HPHPc not having ZendCompatMode classes removed this should be safe

Reviewed By: @markw65

Differential Revision: D989366
2013-10-02 11:01:12 -07:00
Paul Tarjan 46624c867e support objects in zend compat layer (take 2)
Now that mark found the issue with HPHPc not having `ZendCompatMode` classes removed this should be safe

Reviewed By: @markw65

Differential Revision: D989365
2013-10-02 11:01:11 -07:00
Yuval Hager 2d7481d97a Data stream wrapped based on RFC 2397 and Zend
Implemented data stream wrapper, based on RFC 2397 and Zend
implementation.

While the patch can read the metadata of a stream, it does not save it
anywhere, and thus will not pass zend's stream meta data tests for RFC
2397.

Closes #1051
Closes #1112

Reviewed By: @ptarjan

Differential Revision: D990460

Pulled By: @scannell
2013-10-02 11:01:11 -07:00
Edwin Smith 1567efb34b Remove PolicyArray
It was a good experiment in modularity, and I think we can do something
similar (but different) in HphpArray.

Reviewed By: @andralex

Differential Revision: D992945
2013-10-02 11:01:10 -07:00
reeze ba83473e8e Implement restore_include_path()
Implement restore_include_path() and make the default include
path consistent with Zend

Closes #1105

Reviewed By: @ptarjan

Differential Revision: D989566

Pulled By: @scannell
2013-10-02 11:01:10 -07:00
Drew Paroski d0bc6d365f Add toVector() and friends to LazyIterableView and LazyKeyedIterableView
Materialization methods were recently added to collections. This adds them
to the LazyIterableView and LazyKeyedIterableView as well so that these
methods will work when called on an object returned by lazy().

Reviewed By: @jdelong

Differential Revision: D990588
2013-10-02 11:01:09 -07:00
Andrii Grynenko 8cb97e74b8 Adding VariantTraits
Adding VariantTraits and changing CacheClientSerializer to be parametrized by Variant.

Opensource commit message:
Moving VariantController into a separate file.

Reviewed By: zhuohuang

Differential Revision: D990915
2013-10-02 11:01:09 -07:00
Herman Venter 430c585068 Recover from fatal errors that occur while generating back trace information after a VM crash.
When the VM crashes the crash reporter tries to generate a back trace for the error report. If the stack trace contains a call to a function with an argument that is an object that cannot be converted to a string, the routine for generating the stack trace will fail, which is not optimal. This difference adds a try-catch to that recovers from fatal errors that occur during back trace generation.

Adding this try-catch modifies the behavior of public PHP function debug_print_backtrace in an observable manner. Arguably it is a desirable improvement, but is a potentially breaking change.

Reviewed By: @markw65

Differential Revision: D992293
2013-10-02 11:01:08 -07:00
Herman Venter 5a261a7a76 Fix cleanup code for s_directory_data in ext_file.cpp.
When an Xbox thread gets destroyed, the destructor for s_directory_data destroyes the Resource in defaultDirectory, which decreases the refcount to the Directory object, which is a sweepable and is reclaimed somewhere else. This leads to double trouble and caused flib/utils/thread/__tests__/ConcurrentThreadsTestCase.php to fail. (Sadly the test case got disabled, so contbuild did not pick this up.) To prevent the double deallocation, I've added a handler for request completion that detaches the Directory value from defaultDirectory. This seems to solve the problem.

Reviewed By: @markw65

Differential Revision: D991808
2013-10-02 11:01:08 -07:00
Andrei Alexandrescu cfee94b1fc CStrRef sucks
This is the first step of a larger campaign of eliminating goofy types from our codebase. Typedef-ing a reference is unrecommended because references are not first class types and therefore things like construction and copying may do unexpected things. In fact search this diff for 'reinterpret_cast' to see some very odd stuff.

Destroy!

Reviewed By: @jdelong

Differential Revision: D983915
2013-10-02 11:01:08 -07:00
mwilliams 13e67d0074 Fix a race in retranslate
Multiple threads can enter retranslate for a tracelet
simultaneously. This is not normally an issue, because only one
will get the write lease. But if we force blocking on the write
lease, they will all wait, and then generate potentially identical
translations (possibly pushing us over the 12 translation limit).

This adds an atomic flag to the SrcDB so that only one of the
threads will make a translation, and the others will re-enter
the head of the tracelet chain (and either find the new translation
or again hit the retranslate service request).

Reviewed By: @jdelong

Differential Revision: D991611
2013-10-02 11:01:06 -07:00
Alex Malyshev ec85633dc4 Implement SORT_{NATURAL,FLAG_CASE}
We had code for natural sorting, but we never set up the SORT_NATURAL
or SORT_FLAG_CASE PHP constants.

Closes #1090

Reviewed By: @ptarjan

Differential Revision: D986738
2013-10-02 11:01:06 -07:00
Edwin Smith afe9d6f420 Remove use of IRTrace::isMain() in layoutBlocks()
Mark all exit blocks Unlikely, then only use likely/unlikely hints
in layoutBlocks().

Reviewed By: @jdelong

Differential Revision: D991320
2013-10-02 11:01:06 -07:00
mwilliams b9ec0e3548 Make SrcDB more compact
Add a GrowableVectorWrapper to make GrowableVector more
compatible with vector, and use it in SrcRec.
Use a CompactSizedPtr to hold the tca and tag for IncomingBranch.

Reviewed By: @edwinsmith

Differential Revision: D991310
2013-10-02 11:01:06 -07:00
Bert Maher 87f1b39ef3 Move runtime helpers out of codegen
This is pure code movement.  After this the only runtime
functions left in code-gen are the ccmp_* family, which I haven't
figured out how I want to deal with yet.

Some of these can probably be cleaned up/killed (you'll notice a few
TODOs that have probably been around for a long time) but I want to
separate that from the code motion for easier review.

Reviewed By: @edwinsmith

Differential Revision: D991360
2013-10-02 11:01:05 -07:00
bsimmers 78394ee3f8 Update NEWS for Tabasco release
Reviewed By: @jdelong

Differential Revision: D990847
2013-10-02 11:01:05 -07:00
Owen Yamauchi 504156e5e7 Get X64 out of emitGuardChecks & transitive dependencies
This was a spurious coupling; the only reason the assembler object was
used was to emit stats-counter increments. I agnostified the interface
to that as well, which turned out to be pretty easy. I'll put a branch
inside emitInc for ARM support.

I discovered that the cc parameter (which was another x64 coupling) was
unused, so I deleted it.

Reviewed By: @edwinsmith

Differential Revision: D991443
2013-10-02 11:01:04 -07:00
reeze 0b28e760d8 Implement USE_INCLUDE_PATH for file functions
Implement File::USE_INCLUDE_PATH for functions eg:
file_get_contents, fopen, file_exists etc.
Closes issue #837 and move tests to good folder, copy dependency file
from Zend PHP for tests

Closes #837
Closes #1110

Reviewed By: @ptarjan

Differential Revision: D989689

Pulled By: @scannell
2013-10-02 11:01:04 -07:00
reeze 8241e041d0 Make clearstatcache() signature Zend compatible
clearstatcache() does nothing, but the function signature is not
the same as Zend so unnecessary warnings are raised.

Closes #1115
Closes #1117

Reviewed By: @JoelMarcey

Differential Revision: D991348

Pulled By: @scannell
2013-10-02 11:01:03 -07:00
Sean Cannella a07669ec8a Merge pull request #1116 from ZDroid/patch-1
Remove ; from command ends
2013-10-01 13:27:40 -07:00
Yuval Hager a5be703be6 mkdir to return false when path already exists
mkdir should return false if the path already exists to match
Zend

Closes #1113
Closes #1114

Reviewed By: @JoelMarcey

Differential Revision: D990897

Pulled By: @scannell
2013-10-01 10:35:27 -07:00
Sean Cannella b9c9e52dc2 SPL autoload handlers should use context of registration
SPL autoload functions need to capture the context in which they are registered and be called in that context. This comes up when a class method is registered as an autoload handler that is private and/or calls private methods -- the accessibility checks fail without using the proper context. Thus, save off a CufIter and use that to invoke the function instead of just a function object. This fixes a Zend test as well.

Closes #1020

Reviewed By: @markw65

Differential Revision: D976387
2013-10-01 10:35:26 -07:00
Bert Maher 8a89de9db9 Increase iterations of some vm-perf benchmarks
big and nbody both have a substantial amount of time spent in
the JIT.  Increase the iteration count to focus on generated code
perf.

Reviewed By: @ottoni

Differential Revision: D990726
2013-10-01 10:35:26 -07:00
Petro Svintsitskyi 9494ff83b8 Fixed incompatibility of str_replace with Zend
Fixed incompatibility of str_replace with Zend

Closes #1106

Reviewed By: @ptarjan

Differential Revision: D989582

Pulled By: @scannell
2013-10-01 10:35:26 -07:00
Paul Tarjan 4471481bc2 make use ($this) an error
matching zend. I killed all the uses of it in www and right before this pushes, I'll kill whatever is left on the wednesday.

Reviewed By: @paroski

Differential Revision: D804982
2013-10-01 10:35:25 -07:00
Paul Tarjan daa7735107 require -z for importer
I thought running all the bad tests would be useful, but it turns out I've never done that. Lets just require you to have a zend checkout

Reviewed By: @scannell

Differential Revision: D988254
2013-10-01 10:35:25 -07:00
Zlatan Vasović fef5bd81a2 Remove ; from command ends 2013-10-01 10:38:25 +02:00
Bert Maher 3c3c94255e Update SSATmp's of locals when we do a CheckLoc
We weren't propagating type information from a CheckLoc in
the region translator, because we weren't updating m_locals to have a
new SSATmp with the proper type.

Reviewed By: @ottoni

Differential Revision: D989639
2013-09-30 17:54:13 -07:00
Owen Yamauchi 24175d6819 Make moveToAlign's interface platform-agnostic
I think we can start sharing little things like this across platforms.
This makes it so that ARM code can call the same function as the x64
code, and we don't need to duplicate anything.

I also cleaned up emitNAryStub while I was at it, since it's only used
with Arity = 1. And the "unreachable" argument was never used.

Reviewed By: @jdelong

Differential Revision: D990058
2013-09-30 17:54:12 -07:00
Sean Cannella 96349221cd prctl is Linux-only
prctl should only be included when using NUMA

Reviewed By: @sgolemon

Differential Revision: D990526
2013-09-30 17:54:12 -07:00
Petro Svintsitskyi 1ff162e05d Substr_compare warning parity with Zend
Zend Compatibility: substr_compare should raise warnings when
offset and length parameters are invalid.

Reviewed By: @alexmalyshev

Differential Revision: D989609

Pulled By: @scannell
2013-09-30 17:53:52 -07:00
Jordan DeLong 24cd5e2f02 Temporarily disable ext_zend tests that rely on arrays
Reviewed By: @ptarjan

Differential Revision: D988751
2013-09-30 17:53:25 -07:00
Herman Venter 6bac5ca129 Do not emit a source context for the full function body when emitting an implicit function return.
When the compiler inserts an implicit function return statement, there is no source context for the return and the source context defaults to the context of the entire function. This causes execution to stop at implicit returns and the debugger to display a bizarre source context. It also causes every single line in a file to be considered a valid breakpoint location, even blank lines and lines with comments. The code for inserting implicit returns now overrides the source context with a dummy and the code for creating the source line map now ignores dummies.

Reviewed By: @mikemag

Differential Revision: D987159
2013-09-30 17:49:44 -07:00
Mike Magruder 706afc5f96 Make exception tests less picky about how many frames it takes to cause a stack overlow
These exception tests use stack overflow, but they were brittle. 5 and 6 were checking the line the overflow occurs on, and I think that was unnecessary. The point of those two is that something doesn't happen on overflow, not the line the overflow occurs on. 3 and 4 want to see that objects left on the stack are destructed. For those I switched to using some counts, and check them in a shutdown function.

With this change all tests in test/quick pass with ASAN on.

Reviewed By: @scannell

Differential Revision: D987024
2013-09-30 17:49:44 -07:00
Drew Paroski 2fae1b16d7 Fix HHVM to correctly handle cases where __toString() returns a non-string
Reviewed By: @ptarjan

Differential Revision: D968210
2013-09-30 12:24:08 -07:00
Drew Paroski d33687616d Don't allow mock classes to extend collection classes
The native collection classes aren't made to support derived classes, and it
would take some work to add such support. This diff adds a check to prevent
classes marked with <<__MockClass>> from deriving from a collection class.

Reviewed By: drussi

Differential Revision: D980050
2013-09-30 12:24:07 -07:00
Bert Maher c6afc85f87 Move translator runtime functions out of code-gen-helpers
That's it

Reviewed By: @edwinsmith

Differential Revision: D989120
2013-09-30 12:24:07 -07:00
Edwin Smith 7b2302dd1e Eliminate IRTrace::m_data
It's just a per-trace field needed in linear-scan.cpp

Reviewed By: @jdelong

Differential Revision: D989097
2013-09-30 12:24:07 -07:00
Edwin Smith 28853bc546 Remove uses of IRTrace from CodeGenerator
We didn't need CodegenState::catchTrace because we could look
it up using m_curInst.  isCatch() was easy to implement on
Block instead of trace, which enabled cleaning up IRTrace a bit
more.  IRTrace::bcOff was only ever referenced for the main
trace, so I moved that field to IRUnit.

Reviewed By: @jdelong

Differential Revision: D988099
2013-09-30 12:24:06 -07:00
Jordan DeLong 4f5aad0253 Clean up memory-manager.h
Reviewed By: @edwinsmith

Differential Revision: D989068
2013-09-30 12:24:06 -07:00
Edwin Smith bd8c9f5b3c Plumb IRUnit through most of the JIT.
Use IRUnit as much as possible, starting at the Translator-x64
level, and plumbing it down through the call tree into individual
stages.

Reviewed By: @jdelong

Differential Revision: D987491
2013-09-30 12:24:06 -07:00
Jordan DeLong 0f0f461a86 Remove a weird shell script from hphp/runtime
Reviewed By: @edwinsmith

Differential Revision: D989102
2013-09-30 12:24:05 -07:00
Bert Maher 3352847e81 Turn off JitEnableRenameFunction in vm-perf tests
We don't use it in prod so this makes the perf tests more
representative of reality

Reviewed By: @jdelong

Differential Revision: D989075
2013-09-30 12:24:05 -07:00
Guilherme Ottoni a0c9a470b1 Fix profile counters for translations with guards on boxed values
Since normally the inner types of boxed values are checked lazily, the
profile counters were being inserted before the inner types were
checked. This was causing translations with guards on boxed values to
be overcounted -- their profile count was being incremented even when
the inner-type mismatched.

This diff fixes the problem by adding an option to
guardType{Local,Stack} to request the inner types to be checked too.
This option is used to eagerly check the inner types in TransProfile
mode.

Reviewed By: @swtaarrs

Differential Revision: D985443
2013-09-30 12:24:05 -07:00
mwilliams 8224f94dcb Make hhvm more numa aware
Makes a number of changes:
 - Binds each server thread to a numa node, and
   sets its default allocation mode to that node
 - Allocates a jemalloc arena for each node,
   and selects the right one at thread startup (
   to ensure that we don't get memory that was
   previously allocated on a different node)
 - Changes thread scheduling to alternate between
   nodes
 - Sets the default allocation strategy for the
   main thread (and non-server threads) to
   interleaved.

Reviewed By: @jdelong

Differential Revision: D974085
2013-09-30 12:23:59 -07:00
mwilliams 0d2e5c4822 Filter out zend-compat extensions in hphp
Otherwise mysterious things happen.

Reviewed By: @ptarjan

Differential Revision: D985277
2013-09-30 10:42:22 -07:00
Alex Malyshev 4159053041 Fix bug with namespaces not being the first statement in a script
Parser::onNamespaceStart already ignores T_DECLARE, but it also
appears to need to ignore ';'. By default, we do not add a
T_CLOSE_TAG for '?>' but we do append on a ';', and this was
throwing off the parser.

Fixes the last fatal in the composer unittest suite.

Reviewed By: @ptarjan

Differential Revision: D984844
2013-09-30 10:42:22 -07:00
Alex Malyshev 6a09dbc367 Fix how 'pipes' argument is handled in proc_open
Zend PHP ignores whatever the 'pipes' reference is pointing to
in proc_open, and just fills it with an array of resources, but
only if they are not null.

Also rename the ChildProcess's classname to lowercase 'process'
to match Zend's output.

This fixes a fatal in Symfony unit tests.

Reviewed By: @ptarjan

Differential Revision: D984996
2013-09-30 10:42:22 -07:00
bsimmers e45e32f162 Make test/zend/good/Zend/tests/bug36759.php less flaky
This recently started failing on my devserver but not on contbuild. I
traced it down to a dependence on the iteration order of
ExecutionContext::m_liveBCObjs. Wrapping it in a function make the objects'
destruction order deterministic.

Reviewed By: @ptarjan

Differential Revision: D987785
2013-09-30 10:42:21 -07:00
bsimmers 0705ea206b Refresh ringbuffer tracing
The binary ringbuffer tracing had bitrotted a little with the
transition to the IR. I also reorganized RingBufferEntry a little to hold more
information and cleaned up the printing code to print more information about
SrcKeys.

Reviewed By: @jdelong

Differential Revision: D985433
2013-09-30 10:42:21 -07:00
bsimmers 3322b171ab Kill fgets_socket_variation1.php with fire
It's flaky on contbuild

Reviewed By: @edwinsmith

Differential Revision: D987629
2013-09-27 10:46:15 -07:00
bsimmers 15f4fa0050 Recompute YieldExpression/AwaitExpression labels on every analysis pass
One of the optimization passes in hphp can remove unreachable
(Yield|Await)Expressions. This leaves the FunctionScope's yield label count in
an inconsistent state, so relabel/count the yields on each pass.

Reviewed By: @markw65

Differential Revision: D982747
2013-09-27 10:46:15 -07:00
mwilliams 9a31235111 Filter out 'out of date' message from composer
We don't want the test failing every 30 days.

Reviewed By: @ptarjan
2013-09-27 10:46:14 -07:00
Nicholas Ormrod 6f4c350f28 Tidied up includes.
Changed '#include "..."' to '#include <...>' where possible.
Where not possible, and where the included file was not obviously local,
marked the include as being Open Source Software.

Reviewed By: @jdelong

Differential Revision: D986815
2013-09-27 10:15:21 -07:00
Edwin Smith 3f79e348cd s/IRFactory/IRUnit/
Rename IRFactory.  No code changes, just renaming.

Reviewed By: @ottoni

Differential Revision: D986168
2013-09-27 10:15:21 -07:00
Edwin Smith a357435762 Move trace ownership to irfactory
This is the first step in making IRFactory be the compilation
unit container for the IR.  IRTrace is not a tree node; the
main trace has exits, but exit traces don't.  Lots of code uses
the main trace as a container for the IR entry point block.

Reviewed By: @jdelong

Differential Revision: D985668
2013-09-27 10:15:21 -07:00
Guilherme Ottoni 9d9dc9fbd3 Add support to profile and retranslate prologues in PGO mode
This diff implements support for profiling and regenerating prologues
in PGO mode.  The new kind of profiling prologue ("Proflogue")
translations are generated in the aProf code region and include a
profile counter, but they don't trigger a retranslation.  Instead, the
prologues are retranslated when the function body entry triggers
retranslation.  At that point, all prologues that had been generated
for that function are regenerated, immediately before the new,
optimized function body is generated.  The prologues are generated in
ascending order of profile count, so that the hottest prologues are
placed closer to the function entry.  Also, for prologues with
associated DV funclets, the corresponding DV funclets are generated
right after the prologue.

Reviewed By: @swtaarrs

Differential Revision: D977255
2013-09-27 10:15:20 -07:00
Paul Tarjan 6a2124828b fix many flakey zend tests
I went through the latest "failed at step" emails and updated those tests to stop sharing filenames and ports.

Reviewed By: @markw65

Differential Revision: D985394
2013-09-27 10:15:20 -07:00
Edwin Smith 8170ae6a6b Clean up headers a bit.
Moved nontrivial methods out of class definitions, and reduced what cse.h
includes to be closer to IWYU, and avoid circular dependencies in another
diff I'm working on, on top of this one.  Also moved definitions of a few
functions declared in cfg.h from ir.cpp to a new cfg.cpp file.

Reviewed By: @jdelong

Differential Revision: D983927
2013-09-27 10:15:19 -07:00
Paul Tarjan 91acd13340 pretty ResourceData in GDB
Can you think of anything better to print than the ID? I can't figure out how to call the `o_toString` methods, and do we want to?

Reviewed By: @markw65

Differential Revision: D985495
2013-09-27 10:15:18 -07:00
bsimmers 059e1c7702 Properly support surprise flags in hhir
hhir used to do a slow exit whenever a surprise flag check
succeeded. This is fine for most things, but can be all sorts of bad news for
PHProf. This diff adds support for calling the surprise flag hooks without
leaving the trace, and should restore some sanity to profiling results.

Reviewed By: @markw65

Differential Revision: D985446
2013-09-27 10:15:18 -07:00
Paul Tarjan f949e9fad6 Remove useless error array
I decide to scrub the entire zend error message, so this array is stupid now

Reviewed By: @markw65

Differential Revision: D985567
2013-09-27 10:15:18 -07:00
Paul Tarjan cfeae7f325 fix gdb script for ObjectData
It looks like this changed out from under the script. Does this look right?

Reviewed By: @markw65

Differential Revision: D985305
2013-09-27 10:15:17 -07:00
Jordan DeLong 24da1bbf2b Wrap array init with assertions about array escalation
{Packed,}ArrayInit is now the only way to create arrays while
assuming no write barriers are needed.  To ensure it's safe, beef up
the assertions in their use.  Fixed a few cases that had incorrect
size estimates.

Reviewed By: @markw65

Differential Revision: D980262
2013-09-27 10:15:17 -07:00
Jordan DeLong 46c3df8c1d Move class constants tables to TargetCache, use Array instead of HphpArray
This was going to make Class 408 bytes, and it seemed
plausible that that could be causing some red cpu time numbers in a
early perflab, so as part of this diff change declInterfaces not to be
a std::vector to pay for it.

Reviewed By: @edwinsmith

Differential Revision: D979850
2013-09-27 10:15:17 -07:00
Jordan DeLong bd0e7a39e8 Make 86pinit and 86sinit invocation not use a raw HphpArray
I had been thinking of changing these to get the information
out of the class without allocating an array (e.g. using special
bytecodes), but it turned out to be easier to do this without changing
that than I thought.

Reviewed By: @edwinsmith

Differential Revision: D979874
2013-09-27 10:15:16 -07:00
Jordan DeLong 40fbe4af8f Remove duplicate call to destructObjects
In hphp_context_exit, we've already called this (before
requestEventHandler shutdowns).

Reviewed By: @paroski

Differential Revision: D979838
2013-09-27 10:15:16 -07:00
Jordan DeLong 9d676b4b87 Use Array instead of HphpArray to implement f_get_method_names
Reviewed By: @edwinsmith

Differential Revision: D978122
2013-09-27 10:15:15 -07:00
Jordan DeLong df07602d08 Implement closure static locals using object props instead of HphpArray
Reviewed By: @edwinsmith

Differential Revision: D976430
2013-09-27 10:15:15 -07:00
Jordan DeLong 2d63f2360b Don't use HphpArray to store static locals; translate StaticLoc* better
Reviewed By: bertrand

Differential Revision: D974604
2013-09-27 10:15:15 -07:00
Jordan DeLong 5446d01ede Use an Array to wrap the TargetCache::s_constants array
In defCns this adds one place where we'll do two lookups
instead of one; the whole thing appears to be on a cold path though.

Reviewed By: bertrand

Differential Revision: D978026
2013-09-27 10:15:14 -07:00
Edwin Smith 51c5cbdf52 Remove the trace setter in gen()
Instructions ultimately want a block to jump to, not a trace,
and the trace setter is in the way of untangling some header
dependencies I have in a separate diff.  This was a big enough
change to factor out separately.

It's essentially a mechanical change, although I changed the
helper functions that create traces to return the first block
instead, for convenience.

Reviewed By: @swtaarrs

Differential Revision: D984304
2013-09-26 11:03:53 -07:00
Fabien Potencier 4d69d593f7 Fix unimplemented PHP ENT_* constants conflicts
Special constants conflict with unimplemented PHP ENT_*
constants in the htmlspecialchars function so raise their values to
avoid confusing frameworks into thinking these are implemented.

Closes #1085

Reviewed By: @markw65

Differential Revision: D980178

Pulled By: @scannell
2013-09-26 11:03:52 -07:00
Mike Magruder 42eea3ae24 Detect and report stack imbalance in TraceProfiler
TraceProfiler maintains a log of every function call and return. By adding the function name to return events we can ensure that a return matches a call when post-processing the log. Too keep the log size small I've stolen a bit out of the memory counter for the trace samples since it's not realistic that we'd need a full 64 bits there.

I've added a little bit of logic to detect a missing return and correct the stack imbalance to keep the rest of the report accurate.

Reviewed By: @swtaarrs

Differential Revision: D983012
2013-09-26 11:03:52 -07:00
Rachel Kroll 1f1154a313 UseNewCache needs to be a compiler flag since that's where it gets used
Move UseNewCache flag to compiler context

zend unit test failing - not connected to this code

Reviewed By: bmaurer

Differential Revision: D983399
2013-09-26 11:03:51 -07:00
Jordan DeLong d07620bd71 Revert "support objects in zend compat layer"
This reverts commit b9516f1895f00da4b458f633b1d36979367e62f5.

Reviewed By: @ptarjan

Differential Revision: D984226
2013-09-26 11:03:50 -07:00
Jordan DeLong 99faf13b3a Revert "import oauth extension (take 2)"
This reverts commit 799f262497a0dbe562906152f585b4cfc0129649.

Reviewed By: @ptarjan

Differential Revision: D984215
2013-09-26 11:03:50 -07:00
Sara Golemon 798a8acaab Ignore SPL CSV artefact 2013-09-26 11:03:35 -07:00
Petro Svintsitskyi b857bc3510 Making str_shuffle more compliant with Zend
Fix randomization algorithm to be in line with Zend

Closes #1087

Reviewed By: @JoelMarcey

Differential Revision: D982028

Pulled By: @scannell
2013-09-25 12:17:13 -07:00
Sean Cannella caae916002 remove extra macro enables for newer gcc versions
- Now that we are compiling with 4.8.1 we don't need this
anymore

Reviewed By: @jdelong

Differential Revision: D951800
2013-09-25 12:17:13 -07:00
mwilliams fa055be581 Move flakey test
fputcsv.php uses a temporary file named fgetcsv.csv,
just like fgetcsv.php does. They collide. Disable fputcsv
pending a fix.

Reviewed By: @jdelong

Differential Revision: D983981
2013-09-25 12:17:12 -07:00
mwilliams 03e5f9a629 Fix rpc timeouts
The timeout was set at the start of each rpc request, but
not cleared at the end, so a timeout could occur between requests,
resulting in the timeout exception being thrown as soon as we
started to execute php code.

Clear the timeout, and the timed-out flag, at the end of each request.
We call http_session_exit at the end of normal http requests,
which already did that, so this issue is specific to rpc requests.

Reviewed By: bertrand

Differential Revision: D983623
2013-09-25 12:17:12 -07:00
Paul Tarjan 2c0a8812d7 fix forcing disabling broken zend test
Missing comma, and bug36759 needs norepo

Reviewed By: @markw65

Differential Revision: D983749
2013-09-25 12:17:12 -07:00
Paul Tarjan bd5e1a7126 stop changing the zend directory structure
I tried to make life nicer for us by having just a flat level of directories, but it turns out lots of zend tests depend on their directory structure. I think we should give up and just exactly mirror them.

Closes #1081

Reviewed By: @markw65

Differential Revision: D981964
2013-09-25 12:17:05 -07:00
Jordan DeLong 8a654d60c1 Add assertions that smart_free's are actually from smart_malloc
Also, I think it's hard to imagine the assert that iterates
the slabs hitting when the magic one doesn't, so I removed that in the
name of debug perf.

Reviewed By: @markw65

Differential Revision: D976926
2013-09-25 11:51:16 -07:00
Guilherme Ottoni 20f1fb5454 Fix post-conditions for stack values
There were a couple of bugs that this diff fixes:

1) Relative SP offsets were being used although the SP was being
adjusted. This was fixed by keeping the post-conditions for stack
values relative to FP, and by keeping the SP offset relative to FP in
each Block.  While doing this, I also realized that the region
translator was always using the live SP offset, so I fixed it to use
the SP offset for it's first block.

2) Values with types Gen and None were being dropped from the
post-conditions, with the effect that older values would be kept in
the accumulated post-conditions during hottrace region selection. I
changed getStackValue so that it only returns None for values that
were neither guarded nor written in the IR trace, and only these are
omitted by getKnownTypes.

3) The accumulated post-conditions was keeping stack values after they
had been popped.

Reviewed By: @swtaarrs

Differential Revision: D972665
2013-09-25 11:51:15 -07:00
Edwin Smith 3d7b00f600 Remove HHIRSimplificationMaxBlocks workaround.
This used to work around a bad O(N^2) blowup in TraceBuilder, but
the blowup was fixed by D830913.  Removing the workaround.

Reviewed By: @jdelong

Differential Revision: D980277
2013-09-25 11:51:15 -07:00
Joel Marcey 6e58b42bf5 Update the OSS PHP Framework test script to support more tests and to support the downloading of Composer and PHPUnit
The OSS PHP Framework test script now supports more tests. Added a custom test command field to tests that don't use the vanilla "phpunit" command to run the tests. Also the code now downloads Composer and PHPUnit instead of relying on them being available in our repo.

Future updates:

- Support the rest of the tests in the tests map
- Support our test/run framework

Reviewed By: @sgolemon

Differential Revision: D981565
2013-09-25 11:50:55 -07:00
Alex Malyshev 399501f7f6 Silence warning for $result = $bad[$key] case when HHSyntax is off
Zend PHP emits warnings for:

  * $bad[$key] = ...;
  * $result = ($bad[] = ...);
  * $result = ($bad[$key] op= ...);

but not the title's case. The warning we emit prevents phpBB and
Drupal from installing.

Reviewed By: @markw65

Differential Revision: D981223
2013-09-25 11:47:03 -07:00
bsimmers 80df48db51 Support unions with specialized types in JIT::Type
This diff adds support for types like {Obj<C>|InitNull}, including all
the operators we have defined on Type. It's necessary in an upcoming region
translator diff. It's not currently used for anything but I thought it was
worth pulling out into a separate diff because of the complexity.

Reviewed By: @jdelong

Differential Revision: D973156
2013-09-25 11:47:02 -07:00
Sean Cannella e6bbf57d81 SimpleXML attribute mismatch
Fix issue and add test re: child attributes not matching upon
return from addChild and enumerating directly. This breaks two other
tests, but these are of lower priority.

Reviewed By: @ptarjan

Differential Revision: D982083
2013-09-25 11:47:01 -07:00
Herman Venter c756800538 Use in memory structures for debug line info
This diff removes the last direct uses of SQL queries for mapping source line information to byte code offsets.

Reviewed By: @mikemag

Differential Revision: D980213
2013-09-25 11:47:01 -07:00
Sean Cannella 059cd7fee1 Fix OSX build
OSX build is broken, fix it

Reviewed By: bertrand

Differential Revision: D981730
2013-09-24 10:11:55 -07:00
Andrew Gallagher 956677bca8 hphp: replace ENABLE_ASAN with FOLLY_SANITIZE_ADDRESS
FOLLY_SANITIZE_ADDRESS is automatically enabled via the

Reviewed By: @scannell

Differential Revision: D978198
2013-09-24 10:11:55 -07:00
Paul Tarjan 6bfde5b6d7 import oauth extension (take 2)
redoing this after the revert

Reviewed By: @paroski

Differential Revision: D976056
2013-09-24 10:11:46 -07:00
Paul Tarjan 8034cb790e support objects in zend compat layer
everything in here was needed to make the oauth extension work

Reviewed By: @paroski

Differential Revision: D976237
2013-09-24 09:54:42 -07:00
Drew Paroski 8e4769756e Fix Set::toKeysArray() and Set::toValuesArray()
Reviewed By: @elgenie

Differential Revision: D981442
2013-09-24 09:54:41 -07:00
Sara Golemon 78663693ff Regard unimplemented functions an non-existant
This can happen when a function is declared
in systemlib, but not implemented in cpp.

Reviewed By: @ptarjan

Differential Revision: D976157
2013-09-24 09:54:40 -07:00
Alex Malyshev 6762be28d0 Don't warn on include'd files that are empty
We currently emit a "File not found" warning on empty files that
are include'd, whereas Zend PHP is silent.

Reviewed By: @markw65

Differential Revision: D977274
2013-09-24 09:54:40 -07:00
Eugene Letuchy 3ff73855e9 update materialize_methods test for Set->toArray() change
... should fix cont build

Reviewed By: @markw65

Differential Revision: D980893
2013-09-24 09:54:17 -07:00
Drew Paroski 5445928064 Update array_keys(), array_values(), array_combine() to support collections
Reviewed By: drussi

Differential Revision: D974413
2013-09-24 09:54:17 -07:00
Eugene Letuchy a063f5394d collections: set-like-array return value from Set::toArray
Set::toArray returns `array(val1 => val1, val2 => val2, ...)`. This
maintains set-like semantics in array() land: O(1) membership test
with `array_key_exists($key, $a)` or `$a[$key]` and iteration with `foreach($a as
$member)`. Int-like strings end up with numerical array keys.

For nice symmetry, the results of `$s->toArray()` are the same as those of
`array_combine(array_keys($s),array_values($s))`

Reviewed By: @paroski

Differential Revision: D970064
2013-09-24 09:54:16 -07:00
Paul Tarjan 86a1fddee9 get ready for ZendCompat classes
This turns off the `ZendCompat` classes at runtime just like we do for functions.

Reviewed By: @paroski

Differential Revision: D976049
2013-09-24 09:54:16 -07:00
Paul Tarjan 6496177f02 pass 'this' to extension functions
with classes, this needs to be passed down as a variable since many extensions just hard-code `this_ptr`.

Reviewed By: @paroski

Differential Revision: D976055
2013-09-23 14:57:25 -07:00
Paul Tarjan a3af3ab7bb add some namespace to macros
I'm using these macros outside the HPHP namespace

Reviewed By: @paroski

Differential Revision: D976050
2013-09-23 14:57:25 -07:00
Rachel Kroll 3dbbf60946 Auto-detect new cache format
Notice new cache format on read

Reviewed By: bmaurer

Differential Revision: D980474
2013-09-23 14:57:25 -07:00
Paul Tarjan f2e5cdc872 fixup newext to handle classes
still needs some love, but it pulls in classes now

Reviewed By: @paroski

Differential Revision: D976054
2013-09-23 14:57:24 -07:00
Eugene Letuchy 93ba44b96c change double-colon to be T_DOUBLE_COLON in the lexer
"Syntax error: unexpected T_PAAMAYIM_NEKUDOTAYIM" is a WTF
 rite-of-passage for every PHP noob. Unlike Zend, we don't have
 history to be beholden to, so HH syntax errors ought to be able to
 complain about T_DOUBLE_COLON. For compatibility with any parsers
 built on Zend, continue returning T_PAAMAYIM_NEKUDOTAYIM in
 'token_name' results

Reviewed By: @jdelong

Differential Revision: D980141
2013-09-23 14:57:18 -07:00
Eugene Letuchy 9248ec70a3 emit casting bytecodes for "<type>val()" funcs
... because the results are equivalent.

Reviewed By: @markw65

Differential Revision: D980174
2013-09-23 13:35:14 -07:00
Eugene Letuchy 8af58e1aeb parity: add the boolval builtin
Added in PHP5.5, this builtin is going to be useful as a
 default argument for functions that expect a predicate callable.
 It's better to implement it than force the user to create yet another
 instance of `function ($var) { return (bool) $var; }`

Reviewed By: @markw65

Differential Revision: D980164
2013-09-23 13:35:14 -07:00
Andrei Alexandrescu 3aa1b9fc01 Reduce compilation time of hphp/runtime/vm/native.cpp from 300+ seconds to 32 seconds.
hphp/runtime/vm/native.cpp generates a combinatorial number of template instantiations (proportional to 4 to the power of maximum arguments allowed), which makes it extremely slow to compile - over 350 seconds on my machine. This change forces all types to a binary-compatible uint64_t, thus keeping the calls well formed binarily (wee, new word) whilst drastically reducing the number of instantiations involved.

Reviewed By: @jdelong

Differential Revision: D979860
2013-09-23 13:35:13 -07:00
mwilliams 7d84012e1a Fix array_cse/537.php
Its producing different warnings in different situations,
so just turn them off.

Reviewed By: @hermanventer

Differential Revision: D980191
2013-09-23 11:19:16 -07:00
Sean Cannella db4babec30 requestInit shouldn't clear Arrays again
On requestInit, if Arrays are null inited and reset during
shutdown, they shouldn't need to be reset again (it will just end up
doing redundant work) so just assert the expectation is the case.

Reviewed By: @markw65

Differential Revision: D978681
2013-09-23 11:19:16 -07:00
Edwin Smith 31f69fede6 Fix emalloc and spprintf
emalloc(n, size, offset) was ignoring the size and offset params,
and underallocating.

spprintf() wasn't allocating & copying the null terminator byte.

Reviewed By: @jdelong

Differential Revision: D979798
2013-09-23 11:19:15 -07:00
Drew Paroski 6ab9544087 Fix traits bug with instance props that use collection literal initializers
This fixes a traits bug involving instance props that use collection literal
initializers. Instances of a class are not supposed to share the collection;
they are supposed to each get their own copy.

Reviewed By: @andralex

Differential Revision: D979933
2013-09-23 11:19:15 -07:00
Drew Paroski 60e51ec61b Add toKeysArray() and toValuesArray() to all collection types
Map and StableMap already have these APIs, let's add them to Vector, Set,
and Pair for consistency.

Reviewed By: @elgenie

Differential Revision: D979552
2013-09-23 11:19:15 -07:00
Louis Brandy 3c8a7e9331 Deprecate boost::shared_ptr
Replacing boost::shared_ptr with std::shared_ptr.

Reviewed By: @andralex

Differential Revision: D932119
2013-09-22 19:06:08 -07:00
Drew Paroski bf27ae19ad Remove view() method from collections, also remove Vector::sort()
The view() method has been phased out in favor of lazy() (which does the
same thing but is more obvious to developers). Let's remove it.

Also, the Vector::sort() method has been deprecated for a while and was
abandoned in favor of making the regular sort builtin functions work with
collections, let's get rid of that too while we're at it.

Reviewed By: drussi

Differential Revision: D979375
2013-09-22 16:07:43 -07:00
Owen Yamauchi 4c99f0b1aa Push CodeBlock->Asm boundary down into CodeGenerator
I finally figured out what the problem was when I tried to do this
before: comparing Asms for identity by taking addresses doesn't fly
anymore. You have to compare their bases. I grepped for "&m_as" and
"&as" and fixed everything I found.

Now, CodeGenerator takes CodeBlocks in its ctor. It still has Asm
members, but I think that's OK -- CodeGenerator is a pretty short-lived
object already, so the Asms inside it are transitively short-lived.

Reviewed By: @jdelong

Differential Revision: D978477
2013-09-22 16:07:43 -07:00
Herman Venter 1969df24b9 Update NEWS for Bobotie release.
Winged it.

Reviewed By: @jdelong

Differential Revision: D979021
2013-09-22 16:07:42 -07:00
Alan Frindell 11032a5fde Refactor SNI support
The SNI code was married to LibEventServer, which made it incompatible with ProxygenServer.  Moved all the libevent specific code into LibEventServer, which actually simplified the Server::enableSSL interface I think.

Reviewed By: @paroski

Differential Revision: D966945
2013-09-21 16:18:34 -07:00
Jordan DeLong 94a7bc303d Move InsertStaticString to unnamed namespace
It's not supposed to be public, and I accidentally left it in
string-data.h

Reviewed By: @edwinsmith

Differential Revision: D977555
2013-09-21 15:58:54 -07:00
Jordan DeLong 35b13a3652 Don't allocate empty memory for empty FixedVectors
Reviewed By: drussi

Differential Revision: D976486
2013-09-21 15:58:54 -07:00
Jordan DeLong 7047119cfb Remove one of the emitLea overloads
We don't need both.  The 3-arg one is also nicer in a lot of
code-gen situations because it checks for InvalidReg.

Reviewed By: @edwinsmith

Differential Revision: D976482
2013-09-21 15:58:53 -07:00
Jordan DeLong 8ba03e7ab3 Fix ~AutoloadHandler to never access its smart members
We potentially create the AutoloadHandler during repro
creation, from various work threads.  (Things are set up enough to
call builtins.)  Then we shutdown the execution context and then run
OnThreadExit handlers.  ~AutoloadHandler can access the memory manager
after it is destructed, triggering the post delete assertions.

Reviewed By: @markw65

Differential Revision: D979498
2013-09-21 15:58:53 -07:00
Sara Golemon 0a2ab071b9 Don't try to unlink a non-existent repo
This'll throw spurious warnings on fresh checkouts

Reviewed By: @ptarjan

Differential Revision: D979499
2013-09-21 15:58:53 -07:00
Herman Venter f040a61a86 Keep source location table in memory so that source line number to byte code offset lookups don't hit the SQL database
Hitting the SQL database with at least two queries every time the debugger needs to map from source line number to byte code offset, or vice versa, makes no sense. This diff adds a table to Unit that can be used instead of the database. Note that when running in repo authoritative mode, the table will be empty because a) it is created lazily when a unit is loaded form the repo and b) in this mode, the repo does not contain the source line information needed for this table. This does not matter too much because we don't support debugging when running in repo authoritative mode.

Note, this diff does not remove all uses of the SQL database. That will be done in a follow up diff.

Reviewed By: @mikemag

Differential Revision: D978834
2013-09-21 15:58:53 -07:00
Jan Oravec b8eae90154 Maintain linked list correctly in Sweepable
In a more complex scenarios where sweep() may unregister() other
Sweepables, linked list was not maintained correctly.

Imagine this example:

  HEAD <-> A <-> B <-> C <-> HEAD

If sweep(A) calls unregister(B) and unregister(A), the following
happens:

  // Sweepable::SweepAll delists A:
  HEAD <-> B <-> C <-> HEAD
  HEAD <- A -> B

  // and calls sweep(A), which calls unregister(B):
  HEAD <-> C <-> HEAD
  B <-> B
  HEAD <- A -> B

  // then unregister(A) that uses invalid pointers from A, creating this mess:
  HEAD <-> B -> B
  HEAD <- C <-> HEAD
  A <-> A

  // Sweepable::SweepAll then tries to incorrectly sweep(B), which
  // crashes stuff

After this diff, Sweepable::SweepAll delists stuff correctly:

  // Sweepable::SweepAll delists A:
  HEAD <-> B <-> C <-> HEAD
  A <-> A

  // and calls sweep(A), which calls unregister(B):
  HEAD <-> C <-> HEAD
  B <-> B
  A <-> A

  // then unregister(A) does nothing:
  HEAD <-> C <-> HEAD
  B <-> B
  A <-> A

  // so Sweepable::SweepAll can correctly continue with sweep(C)

Reviewed By: bertrand

Differential Revision: D979013
2013-09-21 15:58:52 -07:00
Paul Tarjan 5583329dd1 put back test 537
@markw65 confirmed we shouldn't expect the warning in repo mode. Either I disable the test in repo mode or make the warning optional. I went with optional.

Reviewed By: @elgenie

Differential Revision: D978593
2013-09-21 15:58:52 -07:00
Max Wang 4478db23d6 Add XboxServer support for asio events
This allows us to treat XboxTasks as external threads in the ASIO
framework.

We template the ServerTaskEvent class so that it may be used in the
future with other similar server interfaces, e.g. PageletServer.  We
expose XboxTransport for use in ServerTaskEvent.

Storing a Transport * in ServerTaskEvent instead of a Resource

Template; expose the Transport type from the Server

Also parametrize the Transport class

Expose XboxTransport

Reviewed By: @jano

Differential Revision: D975697
2013-09-21 15:58:52 -07:00
Drew Paroski edfdb8f113 Add toVector(), toMap(), toStableMap(), toSet() methods to collections
These methods provide a convenient way to materialize a lazy iterable into
a concrete collection, or to convert from one collection type to another.
Doing "$x->toX()" is equivalent to "new X($x)" (where $x is an Iterable
and 'X' is a collection type), but it's nice to have for the chaining use
case, ex:

  $v = $m->lazy()
         ->map(..)
         ->filter(..)
         ->toVector();

Reviewed By: @elgenie

Differential Revision: D978191
2013-09-21 15:58:52 -07:00
Alex Malyshev 6a627e0648 Make DOMDocument::getElementById actually return DOMElement
We were blindly returning a DOMText object for
DOMDocument::getElementById when it should return a DOMElement.

Reviewed By: @ptarjan

Differential Revision: D967622
2013-09-21 15:58:51 -07:00
Owen Yamauchi 4851fe492c get_class_vars should autoload
This has been wrong for two years (and I got it wrong originally :/ ).
It also turns out that it returns false instead of fataling if the class
isn't found.

Because PHP, get_class_methods doesn't work this way, in case you were
wondering. It returns NULL on error.

Reviewed By: @ptarjan

Differential Revision: D976416
2013-09-20 13:34:40 -07:00
mwilliams ee1f71001a Fix guard pages for thread stacks
I noticed a couple of issues:
 - the stacksize returned by pthread_attr_getstack includes the
   guard size, so we should adjust both the start and the size
 - if you call pthread_attr_setstack, its your responsibility to
   mprotect the guard region

Reviewed By: @jdelong

Differential Revision: D976923
2013-09-20 13:34:39 -07:00
Eugene Letuchy 9e0ded35b0 rename c_SimpleXMLElement::{ToBoolean=>ToBool} to match Collections
for great consistency. Depends on D964614.

  failure due to www test impacted by dependent commit (since fixed)

Reviewed By: @jdelong

Differential Revision: D976094
2013-09-20 13:34:39 -07:00
Eugene Letuchy 3f5cd52a93 collections: support converting to boolean
to simplify the migration story from array(), it makes sense
 to be able to write idiomatic code like:

   $x = $foo->getCollection();
   if ($x) { // ... collection not empty }

 As opposed to the current:

   $x = $foo->getCollection();
   if (0 !== count($x)) { // ... collection not empty }

 The methodology here is very similar to what collection::ToArray does
 (including helpers around static_cast and const access).

 Failure due to broken logic www test that
 I've disabled and the zend test disabled by jdelong in {D978088}

Reviewed By: @paroski

Differential Revision: D964614
2013-09-20 13:34:39 -07:00
Jordan DeLong e1bb8fe491 Move new failing zend stream test to bad
This looks to come from D967885.

Reviewed By: julk

Differential Revision: D978088
2013-09-20 13:34:38 -07:00
Jordan DeLong f665e5656d Use MakePacked in bytecode.cpp instead of doing it by hand
Smith noticed this could reuse the existing creation
functions.

Reviewed By: @edwinsmith

Differential Revision: D975127
2013-09-20 13:34:38 -07:00
Owen Yamauchi d8b452a3cd Finish refactoring service requests: move code, get Asm out of interface
I moved the top-level "emitServiceReq" functions (which don't output any
code themselves) into service-requests.h so they can be shared by the
ARM backend. They will conditionally call either X64::emitServiceReqWork
or (the to-be-written) ARM::emitServiceReqWork.

Reviewed By: @jdelong

Differential Revision: D977213
2013-09-20 13:34:37 -07:00
Andrei Alexandrescu 2c11e1c92d Make sure no decRefs are evaluated during sweeping
We're trying to make sure that destruction/sweeping of extensions is implemented properly. During sweeping there should be no reference decrementing and no smart memory freeing.

Reviewed By: @jdelong

Differential Revision: D932364
2013-09-20 13:34:37 -07:00
Joel Marcey 5fb006a29f Remove Hack comment
Removing the Hack comment from the script

Reviewed By: @sgolemon

Differential Revision: D977342
2013-09-20 13:34:36 -07:00
Jordan DeLong 29bc317436 Eagerly hash shared variant strings
Right now, we wait until the first request that needs the
hash, and it stores it back to the shared StringData.  This removes a
branch from hashHelper, but it doesn't seem to matter.

Reviewed By: @edwinsmith

Differential Revision: D970437
2013-09-20 13:34:36 -07:00
Sara Golemon 8d3fb0de01 Fix libevent linking
Closes #1080
2013-09-20 13:31:43 -07:00
Joel Marcey 010461f180 update with a link to the wiki page around oss frameworks 2013-09-20 10:17:07 -07:00
Sara Golemon 8a5f5ce410 Remove experimental/exception_tracer/StackTrace from our folly fork 2013-09-19 15:31:26 -07:00
Joel Marcey 99eb634b89 Add command_line_lib.php utility script 2013-09-19 14:43:51 -07:00
javer 42d84fcb93 Add support for text node attributes in SimpleXML
Adds support for text node attributes in SimpleXML. This is
needed by Symfony 2 unit tests.

Closes #1077

Reviewed By: @sgolemon

Differential Revision: D976401

Pulled By: @scannell
2013-09-19 14:18:13 -07:00
Yuval Hager e41dfc1c8f Recursion protection during autoload
Prevent infinite recursion in spl_autoload

Closes #1076

Reviewed By: @markw65

Differential Revision: D975429

Pulled By: @scannell
2013-09-19 14:15:34 -07:00
Sara Golemon da07e05d84 Enable double returns from native func calls
FCallBuiltin will still not reach this point
since IDL functions with double args/returns won't be
flagged for native calling.  Native function calls
can still use this path via FCall with an ActRec, however.

Reviewed By: @jdelong

Differential Revision: D976614
2013-09-19 14:15:34 -07:00
Edwin Smith 210c6bd72e Rename SharedMap to SharedArray
Reviewed By: @jdelong

Differential Revision: D976491
2013-09-19 14:15:33 -07:00
Edwin Smith 5e7b64038e Unconditional 8-bit DataType
I noticed this opportunity when reviewing D966781; even though
we have packed_tv turned off for now, there's no good reason we
can't make the DataType enum always be 8 bits.

Reviewed By: @markw65

Differential Revision: D976339
2013-09-19 11:27:47 -07:00
Igor Canadi 68a305c3ae Spliting IR Concat opcode
Added ConcatStrStr, ConcatStrInt & ConcatIntStr opcodes that get emitted based on argument types.

Reviewed By: @jdelong

Differential Revision: D969956
2013-09-19 11:27:46 -07:00
Edwin Smith cbdbbbcd82 Rename a few shared classes, plus cleanup
Use Packed and Array vs Vector and Map, to un-overload those
terms some more.  Also rename fields, flags, and delete a
few clear methods.

Reviewed By: @jdelong

Differential Revision: D975067
2013-09-19 11:27:46 -07:00
Joel Marcey bfe482eede Refactor and update the OSS Framework Test Runner Script
A better version of the original script I sent out yesterday. Includes all our relevant frameworks in the framework map. Some are commentedout still since they need to be special-cased or has some other special requirement. A bit more robust as we are not hardcoding many paths to files like "composer.json". Refactored the code a bit. Also added a zend binary since hhvm balks at some of the dependency installs (e.g., symfony). Zend is there as a sort of failsafe mechanism.

Reviewed By: @ptarjan

Differential Revision: D975570
2013-09-19 11:27:46 -07:00
Edwin Smith 68492a07d9 Factor out common insert code
Every insert method for "Mixed" (set, setRef, etc) uses the
same code; factor it out.  This approach to factoring avoids needing
to pass around strhash_t, which enables using a template;
string and int-specific key handling code is all inside the
overloaded insert() methods.

Reviewed By: @andralex

Differential Revision: D972465
2013-09-19 11:27:45 -07:00
Paul Tarjan 178a25d0fc actually always assert
facepalm
strings are truthy

Reviewed By: @paroski

Differential Revision: D974418
2013-09-19 11:27:45 -07:00
Paul Tarjan 055358e54a disable test/slow/array_cse/537.php
so this test is actually busted in repo interp. We don't emit

  -HipHop Notice: Undefined index: 1 in %s/test/slow/array_cse/537.php on line 53

I'll fix it but reverting it for now

Reviewed By: @elgenie

Differential Revision: D976067
2013-09-19 11:27:45 -07:00
Eugene Letuchy fe88a38bf3 test runner: mention automain mode in the README
... in case people have questions

Reviewed By: @scannell

Differential Revision: D976000
2013-09-19 11:27:45 -07:00
Eugene Letuchy 2d013067ca test runner fixup: allow .hhas in interp mode
Reviewed By: @jdelong

Differential Revision: D975970
2013-09-19 11:27:44 -07:00
Rachel Kroll e9c8f2f0ba Connect existing file-cache to new cache code (default OFF)
Connect existing file-cache to new cache code (default OFF)

Reviewed By: bmaurer

Differential Revision: D971524
2013-09-19 11:27:44 -07:00
Jordan DeLong 918b4ca8f2 Revert "import oauth extension"
This reverts commit 854c24aede111f067ff0bca80f22e9f55eebd170.

Reviewed By: @ptarjan

Differential Revision: D975891
2013-09-19 11:27:44 -07:00
Sean Cannella 84b6b688e1 Fix read overflow in ReadOnlyArena::allocate
ReadOnlyArena::allocate was using the alignment rounded-up
length instead of the original length when std::copying into the arena

Reviewed By: @meyering

Differential Revision: D974955
2013-09-19 11:27:43 -07:00
Eugene Letuchy b6a82f5798 test runner: can now list the failing tests in a file
... to ease xargs usage. The file is either in /tmp , or in the specified ## --failure-file ##

Reviewed By: @ptarjan

Differential Revision: D974430
2013-09-19 11:27:42 -07:00
Eugene Letuchy 655911d939 test runner: add -m automain
Adds a small script for surrounding the contents of a test/*.php file
 with a main() function and a require_once, and a mode to the test
 runner script to do so.

 The script is not foolproof at the moment ... it doesn't deal well
 with the $GLOBAL access, backtraces, etc. Future work will be
 necessary to deal with (heuristic) recognition of such cases.

Reviewed By: @ptarjan

Differential Revision: D974395
2013-09-19 11:27:42 -07:00
Paul Tarjan 7cfd02c82e add RefDataPrinter
While I was in there I cleaned up `SmartPtrPrinter` because I wanted to subclass it, but this turned out to be easier than I thought. Want those changes in here too or just `RefDataPrinter`?

Reviewed By: @markw65

Differential Revision: D975469
2013-09-19 11:27:42 -07:00
Sean Cannella 4961ecc5a6 Fix read overflow in concurrent_shared_store
ASAN detected a read overflow here and I can't convince myself
this code is 100% safe. Since we're comparing StringData anyway, the
size is readily available without (re)calculating it so we mightaswell
use it.

Reviewed By: drussi

Differential Revision: D974599
2013-09-19 11:27:42 -07:00
Paul Tarjan eca2329063 fix gdb numbers
They were changed in the master but not updated

Reviewed By: @jdelong

Differential Revision: D975334
2013-09-19 11:27:41 -07:00
Mike Magruder b26df635ee Greatly increase the speed at which profilers get allocated memory data.
The hotprofiler extension had its own code for asking jemalloc how much memory has been allocated and freed, which called into jemalloc every time. Switched to using the pointers to the actual data that MemoryManager also uses, exposing them from MemoryManager.

Reviewed By: @swtaarrs

Differential Revision: D973767
2013-09-19 11:27:41 -07:00
Paul Tarjan 62aab53128 fix test/slow/array_cse/537.php
add a `<?php`. If I had to guess, the original test didn't have it by accident (back when tests were strings in C++).

Reviewed By: @elgenie

Differential Revision: D975031
2013-09-19 11:27:40 -07:00
Eugene Letuchy 7c6f003db1 new ReflectionMethod($instance) for falsy objects and non-existent methods
* check the __construct "functionality" that ReflectionClass::getMethods relies on explicitly
 * don't implicitly (string) convert a passed-in $instance if the method doesn't exist

 Needed for {D964614}

Reviewed By: @paroski

Differential Revision: D973579
2013-09-19 11:27:40 -07:00
Paul Tarjan 825eb8ee5e zend ext import script
I keep doing these steps by hand so I made a script. This will evolve but it should be ok for now. Once newext.php exists for HNI (or there is a converter I run after) I'll change to that. If if this starts sucking I'll have to gen the signatures from the source code...

Reviewed By: @paroski

Differential Revision: D966326
2013-09-19 11:27:40 -07:00
Paul Tarjan 12e127ff96 import oauth extension
This was a monster. I had to get all the class things working. I'm not perfectly happy with the solution (I haven't worked out if storing a handle in the ZendObjectData is correct or if the ZendObjectData should BE the handle) but as I see more class based extensions they should clarify.

Reviewed By: @paroski

Differential Revision: D957054
2013-09-19 11:27:40 -07:00
javer bdcdd9f1f7 Fix SimpleXMLElement xpath crashes
Set m_root properly when using __construct() or Clone()

Closes #1067
Closes #1069
Closes #1074

Reviewed By: @ptarjan

Differential Revision: D974502

Pulled By: @scannell
2013-09-19 11:27:38 -07:00
Jordan DeLong 6692e056f7 Fix direct use of HphpArray in pack_args_into_array
Use PackedArrayInit.  Also, this function is only called when
there is no invName, but it was doing the magic call case in this case
(we null it first), so rename it and don't branch on that and move it
to the single caller.  Also, it was using appendWithRef instead of
append, presumably because it used to be possible for it to be used
for non-magic calls or something.  From what I can tell, __call can
never get the argument array with reference members (if it can, the
translator is the one doing it wrong).

Reviewed By: @markw65

Differential Revision: D972302
2013-09-19 11:27:37 -07:00
Jordan DeLong 7c0c3daccc Port a few more array initializations to init helpers
Also, adds task TODO's with all the remaining untracked array
uses that I could find (if there's more, they aren't findable via
grep, but I have a plan to catch them with assertions later).

Reviewed By: @edwinsmith

Differential Revision: D972299
2013-09-19 11:27:37 -07:00
Jordan DeLong ab801de2ba Change a few direct ArrayData/HphpArray uses to Array
Also, add comments on the other ones I've found for ->set().
The biggest thing here is sorting out static property initializers
(probably the answer there is to make them not even use arrays).

Reviewed By: @edwinsmith

Differential Revision: D972067
2013-09-19 11:27:37 -07:00
Sean Cannella 8ae54811e5 Fix vixl compilation without USE_JEMALLOC
Vixl doesn't compile without USE_JEMALLOC currently

Reviewed By: @edwinsmith

Differential Revision: D974530
2013-09-19 11:27:36 -07:00
Sara Golemon 69f4567317 Macroize systemlib embed function 2013-09-19 11:26:24 -07:00
seanc fb79922229 Split repo test runs into two
Summary: RepoAuthoritative test runs take longer than normal so split
them into two in order to avoid triggering the Travis timeouts

Reviewed By: @ptarjan
2013-09-18 19:21:12 -07:00
Abel Nieto f391cb397d Support arbitrary expressions inside empty()
PHP 5.5 now supports arbitrary expressions inside the empty() construct. We want to match Zend's behaviour.

For the newly supported cases, empty(E) is equivalent to !(E).

Reviewed By: @paroski

Differential Revision: D966136
2013-09-18 15:27:03 -07:00
Abel Nieto 6dac173dd5 Allow traits to implement interfaces
Add runtime support for implementing interfaces from traits.

e.g. if a class C uses a trait T that implements an interface I, then C is a subtype of I.

Reviewed By: @paroski

Differential Revision: D969512
2013-09-18 15:26:11 -07:00
Sara Golemon 599fa53790 Strip local paths and copy hphp.tab.cpp to hphp/compiler/parser 2013-09-18 15:26:10 -07:00
Guilherme Blanco 3b7f782882 Implemented SPL RegexIterator
Draft implementation of SPL RegexIterator

Closes #504
Closes #1061

Reviewed By: @ptarjan

Differential Revision: D972519

Pulled By: @scannell
2013-09-18 11:07:22 -07:00
Sean Cannella 677196ace0 Fix read overflow in xbuf_format_converter
xbuf_format_converter uses appendstring which currently
assumes its input is a null-terminated string and copies the NULL. The
result ends up being correct even though what xbuf_format_converter
passes to it isn't null-terminated because each extra byte is
overwritten by subsequent calls and the last byte is manually set to
NULL at the end of the function, but it's still trying to potentially
read garbage.

This caused three different extension tests to fail because of their use
of vspprintf which ultimately calls xbuf_format_converter.

Reviewed By: @edwinsmith

Differential Revision: D973694
2013-09-18 11:07:22 -07:00
Paul Tarjan e6e3f722c2 stop using static string in zend compat layer
I didn't know how to do this properly. Drew taught me.

Reviewed By: @paroski

Differential Revision: D974161
2013-09-18 11:07:21 -07:00
Sara Golemon 6618efdde4 Remove HHVM_FBMAKE override of system/constants.h path
The old build system is dead.

Reviewed By: @ptarjan

Differential Revision: D972026
2013-09-18 11:07:21 -07:00
Paul Tarjan c0db288cba make callCustomInstanceInit require there be an __init__
I'm debuggin a thing that throws `Exception` subclasses and I saw this method is always protected by checking a bit on the `Class*`.

Reviewed By: @jdelong

Differential Revision: D973603
2013-09-18 11:07:21 -07:00
Joel Marcey 5b3b5880f5 Write a script to help automate the running of PHP OSS Framework unit tests
This is an initial verison of a script that will allow us to unit test all
of the OSS PHP frameworks that we care about for parity. A more detailed
summary is available at the top of the code, but here are some highlights:

- Autodownload of frameworks; not added to our official repo
- Mulit-process test runs
- Full phpunit stats in a file after each run
- Summary file for all tests run showing pass percentage. Appended with latest
  result for multiple test runs of a given framework. Initial inspiration for
  this file was for our MPK TV parity chart population.

Future:

- Integration with our "test/run" infrastructure
- Special case frameworks that don't use PHPUnit
- Enhance the script to allow "diff" stats that specify what changed from the
  previous run of a test of a framework to the current test (beyond pass
  percentage). For example, what tests caused the pass percentage to increase
  or decrease.

New Files for this diff:

- oss_framework_test_script: The script
- phpunit.phar: Used to actually run the phpunit tests for each framework
- composer.phar: Used for installing framework dependencies for phpunit
- sample_multiple_test_config.cfg: A sample configuration file to run multiple, but
  not necessarily all testsi

NOTE: I am only including 3 of the OSS frameworks as part of the code for this diff.
When this diff is accepted, I will send out another diff with the rest added. Having
just 3 makes for easier initial testing.

Another note: I removed the comment that command_line_lib does not support options with
arguments. It does. I am using that functionality in this script.

THANKS TO @ptarjan for process ideas from both running the tests and getting through
the proxy!

Reviewed By: @ptarjan

Differential Revision: D971897
2013-09-18 11:07:20 -07:00
Drew Paroski 4e5773ad81 Rework the Zend compat layer to be more robust
This diff reworks the PHP extension compat layer to be more robust by
taking steps to reconcile the difference between mainstream PHP's way and
HHVM's way of representing program values and operating on program values.
This includes the shape of the object graph in the heap (what points to
what), how refcounting is done and how "reffiness" is handled, how copy-
on-write semantics are honored, and how values are stored into arrays.

One of the core ideas here is that HHVM supports "boxing" a program value
via the RefData type and that there's a reasonably clean mapping between
PHP's object graph and HHVM's object graph (when HHVM program values are
"boxed") that maps PHP "zval" objects onto HHVM RefData objects. For the
purposes of a compat layer for PHP extensions, it makes sense to use
RefData to represent "zvals". Of course, it is unreasonable to box every
program variable in HHVM since this would hurt performance. However, we
can make things work by boxing program values lazily as needed in the
right places to ensure that Zend PHP extensions only deal with boxed
values. Along the way I also fixed a bug where we were leaking all of
the arguments that were passed to Zend PHP extension functions.

The next issue involves "reffiness". At present, HHVM RefDatas are treated
as "reffy" when their refcount is 2 or greater, while Zend PHP zvals have a
separate flag (independent of the refcount) that indicates whether they
should be treated as "reffy". Zend PHP extensions are capable of setting
two or more program variable to point to the same zval where the zval's
"reffy" flag is set to false. In such cases, the program variables share
the zval using copy-on-write semantics, where the zval must be copied
before making a modification. To make this work, we need to change RefData
somehow so that we can keep track of whether copy-on-write is needed when
the refcount is 2 or greater. Adding "reffy" flag directly poses some
challenges in terms of performance, because it means that when a value's
refcount decreases from 2 to 1 we'll need to make sure the "reffy" flag
gets cleared. I was able to avoid this by adding two flags (m_cow and m_z)
and creating a scheme that maps the 3-tuple (m_count, m_cow, m_z) to the
2-tuple (realRefcount, reffy). Under this scheme decRef continues to work
as it does today, decrementing the m_count field and calling a helper
m_count reaches zero. Another neat thing about this scheme is that m_cow is
set to 1 iff copy-on-write would be required before modifying m_tv. (NOTE:
This diff does not implement copy-on-write yet for these cases, it will be
addressed in a later diff.)

Another issue is the relationship between strings/arrays and the
zvals/RefDatas that point to them. Under Zend PHP, it is assumed that a
zval exclusively owns the string or array and that nothing else points to
the string/array. A consequence of this is that Zend PHP extensions do not
perform any copy-on-write checks with the string or array's refcount before
modifying the string/array. HHVM on the other hand supports sharing strings
and arrays between multiple RefDatas and/or program variables. Thus, we
need some way to protect against Zend PHP extensions modifying a string or
array when its refcount is 2 or greater. This is achieved by putting checks
in the right places to lazily make a copy of the string or array (when
refcount >= 2) so that Zend PHP extensions only deal with strings and
arrays with a refcount of 1.

Finally, the Zend PHP APIs for adding values to an array are a little
different. Zend PHP extensions pass a zval to the API, and the appropriate
array slot is set to point at the zval. The API does not increment the
zval's refcount; it is the caller's responsibility to do this is needed.
New APIs were added to HphpArray to address this need.

With this in place, the next things to go after would be (1) Fixing up how
the Zend compat layer deals emulating Zend PHP string macros and
operations, this may require adding a new KindOfZStr type if StringData
can't be adapted without hurting HHVM performance; (2) Adding checks in the
right places to make a copy of a RefData if m_cow is 1, I've found most the
places where this is needed and it doesn't look like these checks will
noticably hurt performance; (3) improving support for resource types and
object types defined by Zend PHP extensions and interoperability with HHVM
extension classes, HHVM resources, and user-defined pure-PHP classes.

Reviewed By: @ptarjan

Differential Revision: D966781
2013-09-18 11:07:19 -07:00
Paul Tarjan 1e8f096231 make stream_select() return buffered reads
If we previously read something into a buffer, but userland didn't consume it yet, we need to pretend that `stream_select()` has data. I took inspiration (and the comment) from php.

Reviewed By: @markw65

Differential Revision: D972453
2013-09-18 11:07:19 -07:00
Julius Kopczewski b2ffe12380 Implementing stream_context_get_options() et al.
Added parameter StreamContext* m_context in the File class. Implemented
function f_stream_context_*() functions mostly by delegating to
appropriate methods added in StreamContext class.

Reviewed By: @ptarjan

Differential Revision: D967885
2013-09-18 11:07:19 -07:00
Julius Kopczewski 32e9e061e4 Interface abstract method reflection bug.
Changed FuncEmitter to mark interface methods as abstract.

Reviewed By: @ptarjan

Differential Revision: D970228
2013-09-18 11:07:18 -07:00
Owen Yamauchi 1a203cd998 Make VIXL use CodeBlock
This lets vixl::Assembler and HPHP::X64Assembler have something
resembling the same interface.

Including data-block.h from vixl exposed a bunch of header issues, so I
cleaned some of it up -- removing dependencies on boost and including
unistd.h in one place.

Reviewed By: @jdelong

Differential Revision: D971335
2013-09-18 11:07:18 -07:00
Sara Golemon 1b251e4124 Collect some stats so that we can tune the travis build a bit 2013-09-17 11:19:41 -07:00
Sean Cannella c20deeec4a remove libunwind dependency (C++)
Remove the include against libunwind and use libgcc instead.

Closes #787
Closes #1046
Closes #1047

Reviewed By: @jdelong

Differential Revision: D971114
2013-09-17 11:08:27 -07:00
Owen Yamauchi 1b8c943e98 Clean up IsType hacks for objects and resources
This was unlocked by separating resources and objects. is_object now
behaves normally (it's just a check for m_type == KindOfObject, instead
of needing to exclude resources), so all the special logic in codegen
and simplifier can go away.

I also replaced the string-type logic with an assert, and added an
equivalent one for array types; the special logic wasn't necessary in
practice because we always pass Type::Str as the tested type. This is
just future-proofing.

Type::Res doesn't need any special treatment because there's no opcode
for is_resource().

Reviewed By: @ottoni

Differential Revision: D970744
2013-09-17 11:08:27 -07:00
Andreas Fischer ce36d82b8e Add ReflectionProperty::setValue(mixed) support
Without this patch, only the two-parameter signature is
supported, i.e. public void ReflectionProperty::setValue ( object
$object , mixed $value )

Closes #1056
Closes #1057

Reviewed By: @ptarjan

Differential Revision: D970665

Pulled By: @scannell
2013-09-17 11:08:27 -07:00
Sean Cannella 15b5c7b61f Fix compilation without USE_JEMALLOC
Fix compilation without USE_JEMALLOC

Reviewed By: @jdelong

Differential Revision: D971542
2013-09-17 11:08:26 -07:00
peter-svintsitskyi c2ec3da9e7 make parse_str more Zend compliant
parse_str should handle its second argument being null

Closes #1063

Reviewed By: @ptarjan

Differential Revision: D971664

Pulled By: @scannell
2013-09-17 11:08:26 -07:00
Paul Tarjan a548507b3d add missing .expect file
I forgot to flatten this in
sosorry

Reviewed By: @jdelong

Differential Revision: D972435
2013-09-17 11:08:25 -07:00
Paul Tarjan 9157d4d085 make stream_set_write_buffer not segfault
If you use proc_open, we get `File` objects that don't have an underlying stream. This shouldn't segfault.

Reviewed By: @jdelong

Differential Revision: D972360
2013-09-17 11:08:25 -07:00
Bert Maher d79fbf2eb0 Remove SPropCache::lookup since it is dead
Rename lookupIR to lookup in its place.

Reviewed By: @jdelong

Differential Revision: D972020
2013-09-17 11:08:25 -07:00
Jordan DeLong cf888c19d7 Convert CREATE_{VECTOR,MAP} from macros to variadic templates
Reviewed By: @andralex

Differential Revision: D970885
2013-09-17 11:08:24 -07:00
Jordan DeLong 55f1f1b2f5 f_eval doesn't really work and isn't an extension function; remove it (take 2)
Reviewed By: @ptarjan

Differential Revision: D907074
2013-09-17 11:08:24 -07:00
Jordan DeLong 9cbcb364f7 Fix a bug when FPushFunc throws an exception
We need to create the catch trace before we pop the object,
since we're throwing with the marker set to before this instruction
has started.  Also it needs Refs, because it can invoke the autoload
map code.

Reviewed By: @ottoni

Differential Revision: D970481
2013-09-17 11:08:23 -07:00
Herman Venter 28fa6c6c2a Parameterize host specific test output
hphp/test/slow/ext_collator/1810.php produces output that is host specific. Renamed expect to expectf and replaced the host specific output with %s.

Reviewed By: @ptarjan

Differential Revision: D971536
2013-09-17 11:08:23 -07:00
Herman Venter 55ca52bc4b Directly restore line table from repo to unit
The line table is a shorter version of the source location table and is needed for run time behavior beyond on-line debugging. When a unit is read from a repo, the line table is converted to a pseudo source location table, which is then converted back to a line table when the unit emitter creates the unit. This line table to source location table to line table conversion seems silly in itself. It also does not round trip faithfully, with the result that code that depends on the line table will behave differently the first time than the second time. This may have be the source of flaky tests in the past. Right now, the debugger's small step flow test fails if run a second time.

This diff gets rid of the conversion and directly propagates the line table from the repo to the unit.

Reviewed By: @mikemag

Differential Revision: D969062
2013-09-17 11:08:23 -07:00
Sara Golemon 147b983f2b Add HNI constant binding
Global constants pushed directly into the global constants table:

  static const StaticString s_mpi("M_PI");
  virtual moduleLoad(Hdf config) {
    Native::RegisterConstantDouble(s_mpi.get(), 3.1415926535);
  }

While Class constants are queued into a temporary table,
then picked up during PCE emit as Systemlib is parsed:

  static const StaticString s_math("Math");
  static const StaticString s_pi("PI");
  virtual moduleLoad(Hdf config) {
    Native::RegisterClassConstantDouble(s_math.get(), s_pi.get(),
                                        3.1415926535);
  }

.

  <?php
  class Math {
    // PI will be injected here at emit time
  }

Reviewed By: @jdelong

Differential Revision: D963642
2013-09-17 11:08:22 -07:00
Sean Cannella 13bd327be9 Fix precoloring read overflow on certain opcodes
For opcodes with a variable number of arguments, if the number
exceeds the number of argument registers, the precoloring hint code will
read overflow.

Reviewed By: @markw65

Differential Revision: D971071
2013-09-17 11:08:22 -07:00
Jordan DeLong 5d88c33195 Replace remaining SmartAllocator use with the MM() size-specified allocator
Reviewed By: @edwinsmith

Differential Revision: D970490
2013-09-17 11:08:22 -07:00
Jordan DeLong be6606a1ee Add some debug assertions in smartMallocSize-related functions
Asserts that the thing being freed came from our allocator
and is not double-freed, and that the size it's being free'd with is
acceptable per the size it was allocated with.

Reviewed By: @edwinsmith

Differential Revision: D970449
2013-09-17 11:08:14 -07:00
Jordan DeLong 4f2b0768a8 Use allocm() to make string capacity to be malloc size classes
When a string is big enough to go to malloc, we might as well
use the whole size class malloc gives back.

Reviewed By: @edwinsmith

Differential Revision: D969024
2013-09-17 11:08:13 -07:00
Jordan DeLong 73a31162ea Debug-fill popped eval stack slots when running in interpreter
Was hoping to catch a bug from D891329.  Only caught a benign
use-after-pop of an ActRec in the unwinder.  Maybe worth it anyway?

Reviewed By: @edwinsmith

Differential Revision: D907772
2013-09-17 11:08:12 -07:00
Dario Russi b567b76f00 Allow ConcurrentTableSharedStore to use a StringData for the hashcode when a StringData is provided
StringData carry the hashcode once it has been computed once and it makes sense not to recompute it when accessing ConcurrentTableSharedStore for APC

Reviewed By: @jdelong

Differential Revision: D969504
2013-09-17 11:08:12 -07:00
Jordan DeLong 6591e6b5ec Don't run session shutdown during request event handlers
These things can run user-level PHP and have to occur with a
still-functional ExecutionContext.  Sara and I think it's reasonable
to consider it part of PSP.  Intended to addresses a bug report from
yermo (https://gist.github.com/Yermo/6528678).

Reviewed By: @markw65

Differential Revision: D965421
2013-09-17 11:08:12 -07:00
Owen Yamauchi e67e31db92 Move most remaining service request code into its own module
This moves the emitBindJmp, emitBindJcc, and emitBindCall functions, as
well as some supporting players, into a new module
service-requests-x64.cpp. The two functions freeRequestStub and
getFreeStub are still in tx64, but I think that makes sense.

The way this structure is turning out still doesn't sit well with me,
but I can't quite pin down why. At least now all the nasty-looking
helpers for the emitBind* functions are behind a clean module boundary,
and the external interface (in service-requests-x64.h) is pretty clean.

Getting the new file compiling forced me to clean up some includes, and
move DataBlock up to the HPHP namespace (it was in Transl before).

Reviewed By: @jdelong

Differential Revision: D957725
2013-09-17 11:08:11 -07:00
Sean Cannella dbe929ba4e Suport attribute for disabling ASan analysis
Our custom unwinder code is something ASan knows it can't
analyze properly per Google's documentation. Add support for disabling
the checks (and cleaned up macro indentation to be consistent in
util.h.)

Reviewed By: @meyering

Differential Revision: D970675
2013-09-17 11:08:11 -07:00
Sean Cannella 5f6a135608 util.h sanitization
Fix indenting and attribute name usage in util.h

Reviewed By: @meyering

Differential Revision: D970714
2013-09-17 11:08:10 -07:00
Rachel Kroll bad7176273 New mmapable file cache for hphp
Intended to replace the innards of file-cache.

Reviewed By: bmaurer

Differential Revision: D965985
2013-09-17 11:08:10 -07:00
Jordan DeLong 5f9aed553d Use an Array smart pointer in emitter.cpp for preparing static arrays
We need it to be checking the return value of set() and
append(), so do this.

Reviewed By: @edwinsmith

Differential Revision: D970500
2013-09-17 11:08:10 -07:00
Jordan DeLong e411d52317 Change ObjectData::o_properties to an Array smart pointer
We need it to be checking the return value of things like
lval even when passing false as the copy param.  Use the shared code.

Reviewed By: @edwinsmith

Differential Revision: D970489
2013-09-17 11:08:09 -07:00
Sara Golemon 7874731698 Drop travis parallelism to -j6 rather than -j8 2013-09-17 11:08:09 -07:00
Edwin Smith 5f8ebf2c7a Rename array_tuple.php test to array_packed.php
One more un-overloading of the 'tuple' terminology.

Reviewed By: @elgenie

Differential Revision: D970656
2013-09-16 11:43:44 -07:00
Edwin Smith 4fd3b597f6 Manually inline HphpArray::addValWithRef to the one place they're used used.
They're only called from one place, and manually inlining them allows
a little bit of code sharing; maybe more over time.

Reviewed By: @jdelong

Differential Revision: D970506
2013-09-16 11:43:43 -07:00
Anna Malova 231a7ad1f5 http_build_query() should only include accessible members
fixed bug #26817 (http_build_query() always grabs protected and private variables)

Reviewed By: @markw65

Differential Revision: D963170
2013-09-16 11:43:43 -07:00
Edwin Smith ce9cf05c02 Rename NewTuple to NewPackedArray and MakeTuple to MakePacked
This un-overloads "tuple", which also refers to one of the new
container classes.

Reviewed By: @jdelong

Differential Revision: D970494
2013-09-16 11:43:42 -07:00
Ben Maurer 97ea7c6f3b Varint encoding for blob helper
Blob Helper is used to serialize and deserialize metadata about
compiled PHP files. This diff introduces varint encoding rather
than fixed length encoding. It saves ~100 MB of the 700 MB sqlite
database.

Reviewed By: @jdelong

Differential Revision: D970359
2013-09-16 11:43:42 -07:00
Edwin Smith afd5fb03bf Separate findForDelete from findForInsert
They're used differently enough that this will aid streamlining each
one separately.  Also, this way, key-type-specific logic in erase()
can be done earlier without extra branches.

Reviewed By: @jdelong

Differential Revision: D970271
2013-09-16 11:43:42 -07:00
Jordan DeLong 280763980f Fix a bug in simplifyConvCellToStr
I messed up propagating the catch trace to the specialized
instructions.

Reviewed By: @edwinsmith

Differential Revision: D970299
2013-09-16 11:43:41 -07:00
Jordan DeLong db011b4be7 Fix debug filling in smart_free
I accidentally removed this in an earlier diff.

Reviewed By: @edwinsmith

Differential Revision: D970458
2013-09-16 11:43:41 -07:00
Jordan DeLong 0bb2a3e225 Move RefData from SmartAllocator to smartMallocSize
Reviewed By: @edwinsmith

Differential Revision: D970440
2013-09-16 11:43:41 -07:00
Sean Cannella 7de9fa371e Enable ASan builds in hhvm
Adds the ability to build with gcc 4.8.x ASan. When doing so,
build with -DENABLE_ASAN. (Right now, this disables jemalloc and our
custom memcpy and wordsame functions that read unused bytes and trigger
false positives.)

Reviewed By: @edwinsmith

Differential Revision: D969240
2013-09-16 11:43:40 -07:00
Jordan DeLong d3bd5bc274 Add Mark's python gdb macros to the repo
In freenode's #hhvm, yermo was asking for advice on how to
inspect hphp arrays from gdb.  We should probably have this in the
repo anyway because it's nice.

Reviewed By: @markw65

Differential Revision: D968542
2013-09-16 11:43:40 -07:00
Jordan DeLong 38fd595342 Allocate HphpArrays in a flat mode instead of using m_inline_data
Gets HphpArrays into a flat mode using MM().objMalloc()
instead of SmartAllocator.  Various optimizations were needed to the
Make functions to get this to work out ok.  Growth still creates a
non-flat HphpArray (leaving a PromotedPayload behind so we know how
big the original allocation was).

Reviewed By: @edwinsmith

Differential Revision: D969431
2013-09-16 11:43:40 -07:00
Jordan DeLong c2f8b8942f Automatically register unique-stubs with gdb
The gdb registration of asm stubs was bitrotted;
semi-automate it.  I'm removing the HIGH_OPCODES support for these
since it's a bit out of date anyway (we can add it back again at some
point if we need it).

Reviewed By: drussi

Differential Revision: D962710
2013-09-16 11:43:39 -07:00
Jordan DeLong 7cfa297dab Move static string map to its own module
Reviewed By: @edwinsmith

Differential Revision: D970170
2013-09-16 11:43:39 -07:00
Jordan DeLong a5225a7707 Move HPHP::Slice<T> to util
And make it actually model the boost concepts it claimed to
model.

Reviewed By: @edwinsmith

Differential Revision: D970168
2013-09-16 11:43:38 -07:00
Jordan DeLong 2318c8e280 StringData cleanup
- const correctness fix for AttachStringMode
  - document almost all public functions
  - move most implementations out of the interface
  - rename mutableSlice to bufferSlice

I stopped short of sorting out toNumeric vs isNumericWithVal (I think
we need to delete Variant::toNumeric), and sorting out stuff with the
conversion functions for now.

Reviewed By: bertrand

Differential Revision: D968558
2013-09-16 11:26:37 -07:00
Bert Maher eb73e1c574 ALWAYS_INLINE decodeVariableSizeImm
This function really wants to be inline, or else it does some
extra pointer chasing.

Reviewed By: @jdelong

Differential Revision: D969698
2013-09-16 11:26:37 -07:00
Sean Cannella c59c7a3612 make test/run error output a bit more friendly
Make the catastrophic error message more clear for non-native
English speakers and make it less likely to occur by checking if the
binary exists first before spawning multiple threads.

Reviewed By: @JoelMarcey

Differential Revision: D969894
2013-09-16 11:26:36 -07:00
Sean Cannella 05c8d63231 ASAN: wrong constant size in asio extension
Fix constant size (otherwise treating them as a KindOfInt64 Variant overruns) as we don't support Int32 constants

Reviewed By: @jano

Differential Revision: D969285
2013-09-16 11:26:36 -07:00
Paul Tarjan 22820d0c89 move tests named "failed" to "failure"
our test runner outputs "failed" for tests that fail and grepping always comes up with this test. No need to have this pain.

Reviewed By: @andralex

Differential Revision: D969683
2013-09-16 11:26:35 -07:00
Alex Malyshev 36efefc052 Remove pointless test.xml
Reviewed By: @ptarjan

Differential Revision: D969850
2013-09-16 11:26:35 -07:00
Alex Malyshev 8f8b61522a Add dummy PharData class to stop composer unit test fatal
Reviewed By: @ptarjan

Differential Revision: D968331
2013-09-16 11:26:34 -07:00
Edwin Smith a5ca12110e Add missing include.
Summary:
Fixes build.  I don't know why this didn't fail earlier, but it's
failing in the open source builds.

Closes #1058

Reviewed By: seanc

Differential Revision: D970243
2013-09-14 07:10:06 -07:00
Edwin Smith 4eb05b745f HphpArray cleanup
Various cleanups that I factored out of other work.
Eliminate ElmInd; it's usefulness is pretty low since we rely on
int32_t for the hashtable storage and ssize_t for locals and
and parameters that pass around array positions.

Renamed a few things for brevity & clarity.
Moved some inline functions to hphp-array-defs.h.
More use of auto, replace Elm* with auto& in several places.
Eliminate a bunch of unnecessary ssize_t() casts.
s/ElmIndEmpty/invalid_index in several places.

Reviewed By: bertrand

Differential Revision: D968744
2013-09-13 12:35:48 -07:00
Alan Frindell d618d28696 refactor LibEvent(Worker|Job) to share code with Proxygen
The proxygen server will use the same basic Worker/Job structure so I created server_worker with the shared logic.  Had to make the templates somewhat complex to avoid the perf hit of virtual functions here.

Reviewed By: @markw65

Differential Revision: D922622
2013-09-13 12:35:47 -07:00
Alan Frindell eae7a664c5 remove invalid assert in http_protocol
http_protocol was trying to assert that every body chunk was NULL terminated.  libevent_server *thought* it was doing this by enlarging the buffer and adding a 0.  POST body data can be binary though (images, video, etc) so if any code was actually relying on the 0 for termination, it was likely wrong.

The proxygen server will not add 0 termination to body chunks, so this assert has to go.

Reviewed By: @markw65

Differential Revision: D923553
2013-09-13 12:35:47 -07:00
Alan Frindell 68a374f227 refactor test harness so it can be re-used
This is so I can run test_server type tests for the proxygen server, which is not in the open source directories.

Reviewed By: @paroski

Differential Revision: D922589
2013-09-13 12:35:46 -07:00
Bert Maher cb59b68e5c Declare instrIsControlFlow constexpr for better interpreter performance
Avoids a call on every interpreted instruction that just computes a statically-known property.

Reviewed By: @jdelong

Differential Revision: D968506
2013-09-13 12:35:45 -07:00
Alex Malyshev 23f9fd7bd1 Have sysdoc.php print an error when it can't access php.net
Reviewed By: @ptarjan

Differential Revision: D967730
2013-09-13 12:35:45 -07:00
mwilliams 3d77d16d6a Cleanup some low_malloc issues
I noticed that the first page of low memory never gets hugified,
because the arena gets setup before main, and we don't know what to
mark huge until we've initialized the runtime options.

By setting the high water mark to 1 below the start of the low memory
arena, and only updating it when we *are* marking pages huge, we can
ensure that the right pages get marked.

I also replaced some jemalloc magic that I had never previously understood
with a simpler (to me) equivalent.

Reviewed By: @jdelong

Differential Revision: D967121
2013-09-13 12:35:40 -07:00
Mike Magruder 61a61b54cc Add the 'set' command to hphpd help, adjust tutorial on '='
Added the set command to the overall list of commands shown in the help. Removed extra equals sign from the tutorial printed when the output from '=' is too long, which was confusing people about how 'set cc' works.

Reviewed By: @hermanventer

Differential Revision: D967395
2013-09-13 12:35:39 -07:00
Bert Maher 78fba72e2d Create specialized helpers for member operations on string bases
Make string indexing operations like $str[$i] faster.

Reviewed By: @swtaarrs

Differential Revision: D965035
2013-09-13 12:32:31 -07:00
Mike Magruder 4c13ecfd6c Update debugger to track async changes
This diff updates the debugger to be able to debug async functions again, after the most excellent optimizations introduced in D946914. Minor updates to be able to identify an async func outside of the emitter, and minor adjustments to get breakpoints on async function names working again. Async stacks were fine, the test just needed to be updated. Stepping over await/yield used to decode the instruction stream around OpContSuspend to determine where execution would continue, but that was annoying and brittle. I recently gave c_Continuation the ability to predict its next execution offset, so I enhanced that a bit and switched to using that, so the debugger no longer cares about the codegen around OpContSuspend and doesn't care about anything around OpCreateAsync. This fixes stepping over suspends within a continuation. To get across the first await, we now notice a OpCreateAsync, step over that operation, then grab the c_Continuation off the top of the operand stack and ask it where the heck it's going.

Reviewed By: @hermanventer

Differential Revision: D965577
2013-09-13 12:32:30 -07:00
Guilherme Ottoni 43e5e73d7a Add support for SideExitGuardStk in getStackValue
getStackValue is now being used to obtain the post-conditions at the
end of profiling translations, which requires supporting
SideExitGuardStk.  This was not necessary before because getStackValue
was never used after the jump optimizations that produce
SideExitGuardStk.

Reviewed By: @swtaarrs

Differential Revision: D966360
2013-09-13 12:32:30 -07:00
Herman Venter a47059b75c Do not use repo to map a PC to an offset range
Unit::getOffsetRange(Offset pc, OffsetRange& range) did two SQL queries to the byte code repository in order to map a PC (offset) to a range of offsets that provide all of the bytecode operations that correspond to a single source statement. The information needed for this map is already recorded in the m_lineTable field of the Unit, so there is no need for a SQL query.

Reviewed By: @mikemag

Differential Revision: D966164
2013-09-13 12:32:29 -07:00
Alex Malyshev 218e4718a7 Don't treat DOMDocument's fields as always set
Fixes the logic in PropertyAccessorMap::isset. This is for a
fatal in Wordpress tests.

Reviewed By: @ptarjan

Differential Revision: D964025
2013-09-12 14:17:50 -07:00
Sean Cannella a2ca9faeac Revert "Revert "make simplexml xpath return original objects""
This reverts commit 20c0a8a3c8bf58239fbd856b7f9a83a4c35844bf.

Reviewed By: @edwinsmith

Differential Revision: D964913
2013-09-12 14:17:50 -07:00
Jordan DeLong b79f3ef9ae Fix BadArgument warnings for non-whole program nemo
Lint can't tell if something is a type alias or an object
unless it sees the file that defines the name.  Check it's not in
WholeProgram mode.

Reviewed By: @markw65

Differential Revision: D965717
2013-09-12 14:17:50 -07:00
Sean Cannella a1d13eba5c add more details on contributing 2013-09-12 12:48:33 -07:00
Sara Golemon 72bdfc702a Use camelCase for namespace functions
Style fix.  Only class static methods should use
initial caps.

The few callsites we have don't need to be changed since they're
using the HHVM_FE/HHVM_ME macros which this diff also changes.

Reviewed By: @jdelong

Differential Revision: D965366
2013-09-11 15:02:43 -07:00
Siva Keshava Popuri 38695ff741 Using generic fb_serialize/fb_unserialize implementation
Using generic template-based fb_serialize/fb_unserialize implementation in HPHP.
Removing errcode from fb_unserialize API, since it's never used.

Reviewed By: alikhtarov

Differential Revision: D959470
2013-09-11 15:02:43 -07:00
Paul Tarjan 51e938d203 expose more POSIX constants
I needed these constants to make the stream wrappers for phar. These seem to fit perfectly with the PHP naming convention so I'm not going to put HPHP_ in them since if PHP exposes them, I'm pretty sure these will be the values.

Reviewed By: @jdelong

Differential Revision: D905770
2013-09-11 11:39:51 -07:00
Sean Cannella 84e39a200d Revert "provide run mode which runs all tests in mode matrix"
This reverts commit 9b68d2bd101b9c200f13c809585077b53bdc1786.

Reviewed By: @edwinsmith

Differential Revision: D964898
2013-09-11 11:39:51 -07:00
Edwin Smith c542106129 Skip vector-ish probe in HphpArray::find(int64_t)
This was a nice hack since lots of arrays are packed, however now that
enough are actually kPackedKind, this test doesn't appear to pay for
itself (not called as often as before, and nearly always false).

Reviewed By: @jdelong

Differential Revision: D963530
2013-09-11 11:39:51 -07:00
Scott MacVicar 5e5e486923 Fix segfault with invalid property
Found this while writing some www code, was about to go OOoh found
something the HPHP team missed. Then I saw I wrote all of this in 2011.
Doh.

Catch invalid property and raise like Zend.

Reviewed By: @ptarjan

Differential Revision: D964511
2013-09-11 11:39:50 -07:00
Bert Maher af08cb8cd1 Create fast paths for member instructions that assume base is an array
Elem operations usually operate on arrays, so factor the
switch table dispatch into a NEVER_INLINE slow path, and do the array
case inline, guarded by a conditional branch.

Reviewed By: @swtaarrs

Differential Revision: D963594
2013-09-11 11:39:50 -07:00
Paul Tarjan 8beff49e56 mark chmod ftp test bad for now
Reviewed By: @markw65

Differential Revision: D964074
2013-09-11 11:39:49 -07:00
Sara Golemon ba906e8dd4 Make SID appear undefined until session_start() is called
Generically, this diff treats an uninit_null constant
as undefined.  Currently, this only occurs with k_SID.

Closes #190

Reviewed By: @markw65

Differential Revision: D960974
2013-09-11 11:39:49 -07:00
Alok Menghrajani 78e62c06ee Allow classes which extend generic classes or implement generic interfaces to differ in their function signature.
There are two cases we don't handle correctly (see unittests). This diff adds a new flag to TypeConstraint to keep
track of type variables.

Reviewed By: @paroski

Differential Revision: D942949
2013-09-11 11:39:49 -07:00
Herman Venter 7c420a7524 Sending the breakpoint list from the client to the proxy clobbers the data structures that track which breakpoints are temporarily disabled
Whenever the client sends a command to the proxy that includes a list of breakpoints, the proxy clobbers its list of breakpoints with the new list received from the client. Unfortunately it also uses its list of breakpoints to track which breakpoints are temporarily disabled because the debugger is currently stopped there. As a result, just listing the active breakpoints while stopped at a break point will cause the next continue command to hit the current break point if more byte codes have yet to be processed.

Reviewed By: @mikemag

Differential Revision: D962443
2013-09-11 11:39:48 -07:00
seanc 8af171dc71 Travis tests should run in interp and repo modes
Summary: Parallelize four builds on the (JIT + Interpreter) X
(RepoAuthoritative + Not) matrix so we have parity on our test coverage
and people can get feedback that repo mode tests are failing on pull
requests

Reviewed By: sgolemon
2013-09-11 09:17:01 -07:00
Bert Maher ff044e40fd Refactor of IssetEmptyElem
Cleaning up the last Elem function of member-operations:

As far as I (or gcc) could tell, the isObj template parameter wasn't
used so I nuked it.

ElemIssetEmptyString was begging for a fast path when the key is an
Int64, so I obliged.  I think there's a bit more fat there but I'll
get to it in a later diff.

Reviewed By: @edwinsmith

Differential Revision: D962556
2013-09-10 15:49:07 -07:00
mwilliams 26e8e0c26a Fix and re-enable a number of "flakey" tests
None of these tests are fundamentally flakey - there
is just a danger of port collision (some had already been fixed
before they were disabled). Appropriate retries - and suppression
of warnings for the intermediate failures - should be sufficient to
make them solid.

Reviewed By: @jdelong

Differential Revision: D963009
2013-09-10 15:49:01 -07:00
mwilliams e7519ef1cd Better fix for stack trace generation
Just set the BFD_DECOMPRESS flag on the bfd, and let
binutils propagate it when it follows .gnu_debuglink.

Reviewed By: @jdelong

Differential Revision: D962978
2013-09-10 13:22:16 -07:00
Paul Tarjan 4228878112 Require a runtime option to turn on ZendCompat
We don't want to expose these to the runtime yet (or ever - by default)

Reviewed By: @jdelong

Differential Revision: D962448
2013-09-10 13:22:16 -07:00
bsimmers c8b7a936c2 Expand JIT::relaxGuards to work during normal translation
This is the last major piece of guard relaxation. It adds support for
reflowing the relaxed guard types, meaning it can be applied to a trace without
leaving it in an inconsistent state. The main benefit of this is that it allows
us to loosen/eliminate unnecessary predictions in the region translator.

Reviewed By: @ottoni

Differential Revision: D943543
2013-09-10 13:22:16 -07:00
Paul Tarjan b2303683f9 update import script to do replace
Needed for the race fix by @markw65

Reviewed By: @jdelong

Differential Revision: D962161
2013-09-10 13:22:15 -07:00
bsimmers 310b1b7d0d Remove some flaky bits from test/slow/ext_socket/ext_socket.php
These two tests have flaked out on a couple diffs recently.

Reviewed By: @ptarjan

Differential Revision: D961944
2013-09-10 13:22:15 -07:00
Alex Malyshev f3b9134c9a Fix behavior of stream_get_contents when default args are used
stream_get_contents was assuming a default 0 for maxlen and offset.
Vanilla php uses -1 as the default for both.

Reviewed By: @ptarjan

Differential Revision: D954736
2013-09-10 13:22:14 -07:00
Alex Malyshev ab8688ccad Fix memory leak + incorrect behavior in fgetcsv()
Mostly making File::readCSV look like the code from Zend PHP,
also required changes to how SplFileObject::fgetcsv() handled its
arguments

Reviewed By: @ptarjan

Differential Revision: D961647
2013-09-10 13:22:14 -07:00
mwilliams caa5a45313 Prevent race with bug39538.php
We'll use our own file instead...

Reviewed By: @jdelong

Differential Revision: D961808
2013-09-10 13:22:13 -07:00
Paul Tarjan 2eb55bc51c fix flakey socket tests
I saw these fail once

Reviewed By: @markw65

Differential Revision: D960622
2013-09-10 13:22:13 -07:00
Sean Cannella 5c33971608 enable Zend tests to be run in repo mode
Most of the Zend tests that work will work in repo mode, so
enable that. Create .norepo files for the rest.

Reviewed By: @sgolemon

Differential Revision: D961424
2013-09-10 13:22:12 -07:00
Jordan DeLong 26abc90832 Convert asm test to use util/disasm.h
Make it so the the output doesn't depend on the version of
objdump that's available, so the test is more stable.

Reviewed By: @andralex

Differential Revision: D960736
2013-09-10 13:22:12 -07:00
Paul Tarjan 5dada613d6 delegate opendir to stream library
Directories should be just like Files. I repurposed the `Directory` resource so it didn't just hold a `DIR`. I tried to copy `File` as much as I could.

I implemented the Phar `opendir` as a re-usable `ArrayDirectory`. It felt a bit weird passing an `Array` to the constructor and then not doing anything during open, but it seemed to match `MemFile`.

Reviewed By: @markw65

Differential Revision: D903572
2013-09-10 13:22:11 -07:00
mwilliams 6f866b243f Fix stack trace generation with compressed debug info
There were two issues:
 - you have to set BFD_DECOMPRESS on the bfd*, or it won't
   decompress compressed sections,
 - if the debug info is in a separate file, linked by
   .gnu_debuglink, libbfd will follow the link, but won't
   propagate the BFD_DECOMPRESS flag.

I changed the code to add the flag, and manually follow the
.gnu_debuglink sections, adding the flag as it goes.

Reviewed By: @jdelong

Differential Revision: D961365
2013-09-10 13:22:11 -07:00
Jordan DeLong 198112895e Reorder HphpArray members some; make ctor/dtor private
Get the data representation all at the end, and keep all
privates non-data members at the end too.  Private ctors (eventually
should be removed and replaced by the Make functions) so we can change
its allocation behavior.  The public members are still in a mostly
random order for now, and I left the bulk of the non-static private
member functions alone.

Reviewed By: @edwinsmith

Differential Revision: D960965
2013-09-10 13:22:10 -07:00
Jordan DeLong d83750405b Remove StringData::copy, clean up ImmutableObj
Replaces use of copy with appropriate calls to Make (or
nothing in the case of class names, which are always static).  Fix
copy construct bug in ImmutableObj, make its header not included in
shared-variant.h, some const correctness and other tweaks.

Reviewed By: @edwinsmith

Differential Revision: D960942
2013-09-10 13:22:10 -07:00
Jordan DeLong 50e75593fb Improve StringData::Make(SharedVariant*)
The StringData inside a SharedVariant caches the hash for the
shared string, but we wait until the first time it is accessed to load
it into the request-local string.  Since we're already loading things
out of the shared memory at creation time, just eagerly load it there.
(It might be zero if no one has hashed it yet: we update it racily
from whichever request hashes it first.)  This diff also shuffles some
code around to avoid extra checks for MaxSize, and removes a few
redundant loads that gcc couldn't remove in some Make functions.  Also
move the code to shared-variant.o, and inline the fast path into its
only caller.

Reviewed By: @edwinsmith

Differential Revision: D960931
2013-09-10 13:22:09 -07:00
Jordan DeLong e1322d52dd Remove string modes except Flat and Shared
Modify the remaining mutation functions so they can
optionally return a new StringData*, and make a new rule that strings
created with MakeMalloc cannot have the mutation functions called.
Then reserve/escalate can both always create flat strings, and
MakeMalloc can create flat strings.

Reviewed By: @edwinsmith

Differential Revision: D960849
2013-09-10 13:22:09 -07:00
Jordan DeLong 0ef276f039 Remove StringData::negate, and just do it at the single caller
Reviewed By: @edwinsmith

Differential Revision: D960782
2013-09-10 13:22:08 -07:00
Jordan DeLong 4fb5df7511 Change StringData::set{Char,} API to return new StringData
I want it to be able to reallocate.  (This diff shouldn't
change any behavior, except adding a test on the return value that
can't ever succeed for now.)

Reviewed By: @edwinsmith

Differential Revision: D960724
Differential Revision: D963394
2013-09-10 13:21:59 -07:00
Jordan DeLong ef35f55f3c Rename the HA ArgType in hhbc.h to LA
Removes an old TODO here from when we removed homes from
HHBC.

Reviewed By: @edwinsmith

Differential Revision: D960900
2013-09-10 13:21:58 -07:00
Sean Cannella 492a51e9ed Move some working Zend tests
move some working Zend tests

Reviewed By: @ptarjan

Differential Revision: D960549
2013-09-10 13:21:57 -07:00
bsimmers bf5f733a8c Fix test/slow/ext_iterator/1800.php.expectf
Directory sizes vary between machines.

Reviewed By: drussi

Differential Revision: D961338
2013-09-10 13:21:56 -07:00
Dario Russi 6ee569fe6a Fix collection cloning refcount
When using collection literals in property initializer the ref count is 2 instead of 1 and the collection leaks

Reviewed By: @jdelong

Differential Revision: D959451
2013-09-10 13:21:56 -07:00
bsimmers 289ff85359 Replace Type::from(RuntimeType|DataType|DynLocation) with constructors
These have always bothered me. They only exist as historical
baggage from back before Type was a real class. I also took this
opportunity to convert everything in the jit to use KindOfAny instead
of KindOfInvalid/KindOfUnknown, mostly to clean up conversions from
DataType -> JIT::Type.

Reviewed By: @jdelong

Differential Revision: D960018
Differential Revision: D963452
2013-09-10 13:21:38 -07:00
javer f4eaa42b8c Improve RecursiveIteratorIterator Zend compat
- Added methods and callbacks: beginChildren, beginIteration, callGetChildren, callHasChildren, endChildren, endIteration, getDepth, getMaxDepth, getSubIterator, nextElement, setMaxDepth.

Closes #1006

Reviewed By: @ptarjan

Differential Revision: D953349

Pulled By: @scannell
2013-09-09 10:44:30 -07:00
Sean Cannella 19da83f2aa fix inlining warnings
Noticed these warnings when building on OSX.

Reviewed By: @jdelong

Differential Revision: D958997
2013-09-09 10:28:10 -07:00
Edwin Smith 313417670c Fix compare() bug in TypeAnnotation::dataType()
Fix comparison logic in TypeAnnotation::dataType(), which was causing
the result of f_hash_algos() to be type-punned from KindOfArray to
KindOfObject.

Reviewed By: @markw65

Differential Revision: D961159
2013-09-09 10:28:09 -07:00
Jordan DeLong 06a9adaa0e Fix bug that omitted VerifyParamTypes on Xhp hints
This was only supposed to omit ?Xhp checks, but I messed it
up ....

Reviewed By: @markw65

Differential Revision: D957536
2013-09-09 10:28:09 -07:00
Edwin Smith 575afa61a8 Revert "make simplexml xpath return original objects"
This reverts commit d44b74fec1c4c01114185cc84009bbb1562ca716.

Reviewed By: @jdelong

Differential Revision: D960763
2013-09-09 10:28:08 -07:00
Sara Golemon 0eb3d989c6 Use correct expectf token.
Need to match more generically

Reviewed By: @ptarjan

Differential Revision: D960619
2013-09-08 23:55:49 -07:00
Edwin Smith 42d955534e Move function definitions out of ir.cpp
Minor cleanup; IRInstruction and SSATmp have dedicated headers,
so might as well organize the function bodies that way too.

Reviewed By: @jdelong

Differential Revision: D960927
2013-09-08 17:47:16 -07:00
Jordan DeLong 6d359a1c76 Remove direct StringData use in fb_compact_serialize
I want to make append() return a new StringData*, so removing
callsites that don't check for that.  StringBuffer should be better
here anyway.  Also fixes an exception safety bug.

Reviewed By: andrii

Differential Revision: D957816
2013-09-08 17:47:15 -07:00
Jordan DeLong ea0f5fa4fb Remove backup_gc for now
It doesn't quite work, so maintaining it is not worthwhile.
We can fish it out of source control history if we want to use it as a
starting point for something later.

Reviewed By: @edwinsmith

Differential Revision: D959811
2013-09-08 17:47:15 -07:00
Jordan DeLong ccc9856aca Fix misuse of InitFiniNode
You can't create these on the stack.

Reviewed By: @edwinsmith

Differential Revision: D960750
2013-09-08 17:47:14 -07:00
Jordan DeLong fb520052ff Some fixes for building stuff with clang
Not that much.

Reviewed By: @oyamauchi

Differential Revision: D954663
2013-09-08 17:47:14 -07:00
Edwin Smith 85a381a725 Initialize addrlen before calling accept()
We were passing a garbage value to accept(), making it fail
intermittently.  (A big value will silently pass and could
corrupt memory).  Apparently the value got randomly smaller
with our switch to gcc 4.8.1

Reviewed By: @jdelong

Differential Revision: D960745
2013-09-08 17:47:13 -07:00
Paul Tarjan 5cb6784dba make extension_loaded() true for all ext_zend
and add skipif to all tests

Reviewed By: @sgolemon

Differential Revision: D958951
2013-09-08 17:47:12 -07:00
Paul Tarjan 7d8a93147f add ftp library
This is a good one. It doesn't need an external library and found a ton of corner cases I screwed up. It also got my stream handling much more solid.

I had to wrap other streams as they came into the extension and then unwrap them on the way out

Reviewed By: @sgolemon

Differential Revision: D945250
2013-09-08 17:47:12 -07:00
Paul Tarjan fd82901a9a build resource part of zend importer
This started off as importing the enchant extension but since that library is horrible to work with, I'm not importing it. The resource stuff will be used by ftp and oauth. I can squash this into them or leave it out.

Reviewed By: @sgolemon

Differential Revision: D943019
2013-09-08 17:47:11 -07:00
Paul Tarjan 3536964a43 import yaml extension
I'm putting this in the facebook directory since I don't want to add yaml as a depedancy for the OSS version. This isn't even in the public version of php.net it is in pear, but I want this to set the precident of how to import pear extensions (until @sgolemon makes us a better way). At least this way we get the unit tests.

Reviewed By: @sgolemon

Differential Revision: D942072
2013-09-08 17:47:04 -07:00
Paul Saab 975c51db9a Export Satellite active and queued counts
The Satellite servers didn't expose how many threads were
running and how many were queued.

Reviewed By: @markw65

Differential Revision: D958689
2013-09-08 16:42:04 -07:00
Sara Golemon b16ffb2853 Ignore warnings from unused attributes 2013-09-08 16:42:03 -07:00
Sara Golemon 15648de282 Only use -Wno-maybe-uninitialized on GCC >= 4.7.0 2013-09-08 16:42:03 -07:00
Sara Golemon dc349e4177 Version agnosticism in sqlite error message
Error message can sometimes read
  "unfinalized statements or unfinished backups"

Differential Revision: D960619
2013-09-06 20:56:30 -07:00
Paul Tarjan b84375ff52 fix 2 trunk tests
1 I accidentally removed the %d which is needed since differnet filesystems report differnet sizes, and the other started emitting warnings since calling `get_class(null);` is bad

Differential Revision: D960488
2013-09-06 19:25:05 -07:00
Louis Brandy d089625a07 boost::{dynamic|static}_pointer_cast -> HPHP namespace
The primary goal here: move the custom overloads for `hphp_raw_ptr` of static/dynamic cast in `Base.h` out of the boost namespace, into HPHP namespace (which already uses normal boost versions). This means all casting, to be consistent, should happen in the HPHP namespace

Differential Revision: D959867
2013-09-06 19:24:01 -07:00
Anton Lunyov 381ab20c73 Hack collections support in json_decode
Two custom flags for json_decode are added:
 - FB_JSON_COLLECTIONS to output Vectors/Maps instead of arrays
 - FB_JSON_STABLE_MAPS to output StableMaps instead of Maps

Differential Revision: D950743
2013-09-06 17:52:39 -07:00
Mirek Klimos 705d2ac5cd Eager execution of async function.
Currently, a call to an async function returns a (Continuation)WaitHandle
object but the excution of the function body doesn't start before await
(or join()) on the WaitHandle is called. This changes it to start the
execution immediately and the control is returned to the caller only
after it's blocked.

Differential Revision: D946914
2013-09-06 17:52:38 -07:00
Edwin Smith 2e778b989e Replace TraceBuilder* with TraceBuilder& everywhere.
We never reseat the pointer, and it's generally a contextual
object where it's used.

Differential Revision: D958964
2013-09-06 17:52:38 -07:00
Sean Cannella feac0f5553 vixl 1.0 -> 1.1
Merge vixl 1.1 into fbcode

Differential Revision: D957520
2013-09-06 17:52:37 -07:00
Owen Yamauchi 25438a204b Fix pseudo-virtual dispatch of ToArray and Clone with collections
Turns out you can override collection classes, if you use the
__MockClass user attribute. We have to use instanceof instead of direct
m_cls comparison.

Also, not_reached() has surprising behavior in build configurations
where ##assert(false)## is a no-op -- because of the not_reached, the
compiler was optimizing out the final else-if branch of the chain,
assuming that it could only go one way. Replaced those
with ##always_assert(false)##.

The implementation of c_Pair::Clone wasn't quite right either -- it
wasn't checking for a user-defined __clone function. You have to go
really out of your way to observe incorrect behavior because of this,
but it's doable. Also the elm0 and elm1 members weren't necessarily
initialized (I think). This change can't hurt, anyway.

Differential Revision: D959327
2013-09-06 17:52:36 -07:00
Sean Cannella a5cfcaea9c Fix crash when registering stream wrappers
Stream wrappers were not being destroyed properly at the end of
a request, resulting in strange behavior / crashes if the same wrapper
was registered across multiple requests. This affects Drupal. Sample
code:

<?php
class stream{
  public $name;
}
stream_wrapper_register("public", "stream");
stream_wrapper_register("private", "stream");
stream_wrapper_register("AA", "stream");
var_dump(stream_get_wrappers());

Closes #849
Closes #1032

Differential Revision: D959563
2013-09-06 17:52:36 -07:00
Edwin Smith 14a716dc2d Use IRFactory& everywhere.
We were randomly using * and &, and sometimes even *const, to
pass around IRFactory pointers, which are never reseated.

Differential Revision: D958962
2013-09-06 17:52:35 -07:00
Jordan DeLong 0bac46ef05 Check for capacity overflows when doing StringData geometric growth
It wasn't checking, which means you can make a string bigger
than StringData::MaxLen---the length you ask for in reserve() the
first time is compared with the max length, but you may end up with
more capacity than that and later calls are only checked against
capacity().  StringBuffer will also use this capacity as if it is
within range.  Also add a checkSane() assertion in the resize path.

Differential Revision: D954757
2013-09-06 17:52:35 -07:00
Paul Tarjan 82dbcb4e41 remove config.hdf from test/slow
I keep adding tests in there and I hate that the warnings aren't in the output. This was pretty straightforward:

1) Delete the config.hdf
2) Run all the tests
3) `./tools/out2expectf.py test/slow/*/*.php test/slow/*/*/*.php`
4) `find test/slow -name "*.except" -exec rm {} \;`
5) Fix other broken things

The things I had to fix by hand were:
a) tests with invalid unicode in them that out2expectf choked on
b) tests whose output is too long for a .expectf file. Thankfully they didn't have any warnings.
c) `strtotime_leak.php` was somehow leaking with the default config
d) some tests are different in repo mode, I'm digging into those now

Differential Revision: D958390
Differential Revision: D959973
2013-09-06 17:52:17 -07:00
Jordan DeLong cae8964702 Fix a bug in interpOutputType
We weren't properly handling OutCInput or OutCInputL.  In
practice this means if we interpOne an Unbox or CGetL3 of a reference
type we could generate code that will fail on a later run if it is not
monomorphic.

Differential Revision: D958269
2013-09-06 16:18:40 -07:00
javer ef209b96d3 Improve substr zend compatibility
Fixed issues with negative and out of bounds start position
and length

Closes #1031

Differential Revision: D959015
2013-09-06 16:18:39 -07:00
Alex Malyshev 0bd3a87e85 Implement str_getcsv, and fix some fgetcsv related issues
str_getcsv is now just a wrapper around fgetcsv

Differential Revision: D958124
2013-09-06 16:18:38 -07:00
Sean Cannella 277ff223ed Make test/run's finding repo compiler more robust
Use hhvm --hphp instead of hphp to find the repo compiler as it
is more portable

Differential Revision: D959508
2013-09-06 13:26:12 -07:00
Sean Cannella b22d6ad04c libmemcached support for all 0.4x+ versions
It turns out the Ubuntu 12.04 image I thought was using 1.0.16
was using 0.44 and OSX was using 1.0.17. This should fix compilation on
libmemcached 1.0.8 - 1.0.16.

Closes #1022

Differential Revision: D957901
2013-09-06 13:26:12 -07:00
Paul Saab f893a6482f Fix stream_socket_recvfrom & stream_socket_sendto
IPv6 addresses for stream_socket methods in PHP must be bracket
enclosed.

Differential Revision: D958537
2013-09-06 13:26:11 -07:00
Jordan DeLong 5c2073fa60 Delete unused hphpc list assignment code
Differential Revision: D959103
2013-09-06 13:26:10 -07:00
mwilliams d676d6002d Assign php token constants based on actual lexer token values
Omit the values from constants.idl.json, and provide them
via hphp.tab.hpp.

Differential Revision: D957423
2013-09-06 10:32:14 -07:00
seanc 133e34b1a6 gcc -Wmaybe-uninitialized is too noisy
Summary: Disable -Wmaybe-uninitialized because it's noisy (even with gcc
4.8)
2013-09-06 09:49:28 -07:00
Sara Golemon 872085ebc2 Add PHP_DEBUG constant
Just as it says on the tin.

Differential Revision: D958042
2013-09-05 19:42:17 -07:00
Paul Bissonnette 8eb0a830da Updating ext_string for benchmark optimizations
String optimizations, this gives us a 40% reduction in cycles for the revcomp benchmark.

Differential Revision: D934224
2013-09-05 19:42:16 -07:00
bsimmers cefc22a58e Fix updateTrackedState for StRef
It was using the wrong src number and always getting nullptr.

Differential Revision: D955583
2013-09-05 19:42:15 -07:00
Sean Cannella 167fe36243 provide run mode which runs all tests in mode matrix
Travis only supports running a single commandline to run tests so provide a
mode where we can run JIT+interp X repo+non-repo now that contributors are
starting to submit contributions that only break in repo mode.

Differential Revision: D957147
2013-09-05 19:42:15 -07:00
Herman Venter 88b4738d2c Disable quick/debugger/list.php
This test is flaky on some dev boxes. Disabling it until task 2558262 is implemented. That should get rid of the flakiness.

Differential Revision: D957673
2013-09-05 19:42:15 -07:00
Herman Venter cfcad8431f Allow class authors to customize the way debuggers display instances
If a class defines method __toDebugDisplay, the variable serializer will call it when serializing with DebuggerSerialize. The resulting value is added as property __PHP_DebugDisplay to the serialized object. If an object with such a property is serialized with DebuggerDump, the serialization of the property is used as the serialization of the object with the property.

Differential Revision: D954810
2013-09-05 19:42:14 -07:00
Sara Golemon 9a2a5e36dc Disable ext_zend_compat extensions for now
@ptarjan is still working on the wrapper and there a few
unaccounted for edge cases.
2013-09-05 19:39:57 -07:00
Jordan DeLong f6899af571 Move InstanceBits to separate module; make Class not friend of things
Aside from instance bits this is pretty straight forward.
Most of the other friends were just directly accessing members instead
of using accessors.

Differential Revision: D953599
2013-09-05 19:39:57 -07:00
Jordan DeLong a251801bcd Put objects in the size-specified smart allocator
With the InSitu string mode, this means we can reuse free'd
ObjectDatas for string memory and vice versa.  Putting both in there
seemed to be better than putting either one and not the other.  It
seems plausible we should get ArrayData in on the situation too.

Differential Revision: D954003
2013-09-05 19:39:56 -07:00
Jordan DeLong 37c825cee0 Replace StringData's Mode::Small with a 'Flat' mode
Instead of a specific reserved small size, any string can be
allocated in situ when it is first created.  For now this doesn't
remove the m_data pointer, and both Mode::InSitu and Mode::Shared will
still promote to the old Mode::Smart when you append.

Differential Revision: D953985
2013-09-05 19:39:56 -07:00
Jordan DeLong 8294a6b98e Add support for a size-specified allocation API to memory-manager
Adds a new API where you tell the manager the sizes of the
objects during free, so it doesn't need to track it internally.  This
is for use with in situ string allocation and moving ObjectData
allocation into the shared free lists.  There are a few things still
needing cleanup in the API here still (e.g. smartMallocSizeBig has to
add sizeof(SmallNode) just so it can be subtracted), but I plan to do
it on top of this diff stack to isolate it from causing any perf
impact.

Differential Revision: D953828
2013-09-05 19:39:56 -07:00
Jordan DeLong 10b1a279de Remove StackStringData
Differential Revision: D938355
2013-09-05 19:39:56 -07:00
Jordan DeLong 5f070ee07b Make GetStaticString() not use StackStringData
Getting rid of StackStringData is helpful for a Mode::InSitu.

Differential Revision: D938354
2013-09-05 19:39:56 -07:00
Owen Yamauchi 0fea2acfc2 Move the "helper thunk" assembly stubs to UniqueStubs
The way these are written makes them impossible to treat equally on
different platforms. I'm not sure if these should go in mainCode or
stubsCode, but I'll try perflabbing both permutations.

Differential Revision: D954716
2013-09-05 19:39:55 -07:00
Anna Malova c7282d5e87 fix bug #50847
fixed bug #50847 (strip_tags() removes all tags greater than
1023 bytes long)

Differential Revision: D952826
2013-09-05 19:39:55 -07:00
Eugene Letuchy 0ca009f40a token_* consistency: obvious fixes
Initially, I just wanted to add a test to make sure that the
 results of token_name / token_get_all / defined T_* constants all
 matched. After adding the test, I noticed some hilarity and fixed it:

 - added T_INSTEADOF and T_YIELD (they're now defined in zend)
 - fixed an off-by-two error in the value of T_COMPILER_HALT_OFFSET
 - reversed T_GOTO and T_CONTINUE being defined with the other's value

 That last one ... I don't even.

Differential Revision: D956958
2013-09-05 19:39:55 -07:00
Paul Saab 494fe69dda Fix socket_sentto_recvfrom_ipv6_udp Zend compatibility
Change the default value for the port in socket_sendto/recvfrom
from 0 to -1.  A port is only required for AF_INET and AF_INET6 sockets,
and a port of 0 has special meaning, so use -1 to signify that a port
was not passed in as a function argument.

Differential Revision: D954831
2013-09-05 19:39:55 -07:00
Jan Oravec 4503977fac Use <?hh in async function tests
Async functions are enabled only with hiphop syntax. Unbreak unit tests
by switching them from <?php to <?hh.

Differential Revision: D956897
2013-09-05 19:39:55 -07:00
Drew Paroski edd2eda8e6 Small fix to the lexer rules for "async"
"async" should be able to be listed in any order with other method modifiers
such as "public", "final", etc. Make it so.

Differential Revision: D941131
2013-09-05 19:39:54 -07:00
Yuliy Pisetsky 45e483d755 Make array_combine empty arrays sane
array_combine with two empty arrays should return an empty
array. This was fixed in Zend a while ago (see
https://bugs.php.net/bug.php?id=34857 and
http://php.net/array_combine ). It can't be useful to anyone to have the
old behavior, and causes SEVs:
https://our.intern.facebook.com/intern/sevmanager/sev/467951399979540

Differential Revision: D949569
2013-09-05 19:39:54 -07:00
Paul Tarjan 59ff74e8de add gettext extension
Very straightforward. I think these zend headers are working. The hardest part was getting my importer to pull in that directory. I think I have to stop flattening them.

Differential Revision: D939269
2013-09-05 19:39:54 -07:00
Mirek Klimos 2d19b092d0 Remove extra code related to continuations in local 0 (D842384)
As far as I can tell this is no longer needed as contination doesn't
live in local 0 any more (D842384, D865745).

Differential Revision: D956184
2013-09-05 19:39:54 -07:00
Drew Paroski bbe600e765 Tweak how the lexer recognizes XHP class names
Some developers reported that "$x=$y?:foo();" failed to parse correctly
when EnableXHP=1. The problem happens because the lexer is a little too
aggressive with recognizing XHP class names and it treats ":foo" as an XHP
class name, and so the statement fails to parse.

This diff tweaks the lexer so that "$x=$y?:foo();" parses correctly when
EnableXHP=1. This was achieved by changing the lexer so that in ambiguous
situations where there is no whitespace before ":foo" it will not treat
":foo" as an XHP class name. This change only affects static method calls,
static property access, and class constant access that use an XHP class
name as a base. Note that this change does not affect how parsing works
when EnableXHP=0.

This diff also updates the regex for WHITESPACE_AND_COMMENTS to support
single line comments that begin with '#'.

Differential Revision: D952602
2013-09-05 19:39:53 -07:00
Jordan DeLong ae9d50eb93 Use StringData::{i,}same in FixedStringMap comparisons
So it can use the inline word-at-a-time comparison thing, but
also just shares code.

Differential Revision: D952995
2013-09-05 19:39:53 -07:00
Dario Russi 50b2cbab07 Fix position of optional user attributes on constructor promoted arguments
Custom attributes were inverted with visibility from 2nd arg on

Differential Revision: D945746
2013-09-05 19:39:53 -07:00
Jordan DeLong 059ee76b62 Shrink IndexedStringMap by 8 bytes
There's 4 wasted bytes inside the FixedStringMap, which we
can reuse for IndexedStringMap's size.  Takes HPHP::Class down to 320
bytes.

Differential Revision: D953063
2013-09-05 19:39:52 -07:00
Jordan DeLong a708d8507f Move Class members around; fix an AtomicSmartPtr bug
HPHP::Class is a bit of a mess.  Regroup various members to
help see what the layout is a little better; mostly stop short of
trying to make the API clearer though.  Made ~Class private and
noticed that AtomicSmartPtr calls incorrectly calls delete from a few
places (the m_parent.reset() in releaseRefs(), for e.g.).  Change some
random junk in unit.h.

Differential Revision: D952969
2013-09-05 19:39:52 -07:00
Jordan DeLong 54d95d17c3 Optimize __invoke
__invoke calls were going to the interpreter---this adds a
translation that loads a Func* off of the Class, assuming it's
"normal".  An __invoke is considered non-normal if it is not on a
closure and defined static.  (PHP 5.5 gives a warning in this case,
but still runs the closure as expected.)

This was going to add 8 bytes to HPHP::Class, so I paid for that by
removing an unused hphp_hash_map in Class.  This bumps sizeof(Class)
down to 440.

Differential Revision: D952952
2013-09-05 19:39:52 -07:00
Sean Cannella e370c2f40b don't try to use mysql connection if connect fails
mysql extension was incompatibly trying to use a connection that was a failed result of mysql_real_connect() for other APIs which is unsupported by mysqlclient. Fixed that.

Closes #1021

Differential Revision: D955216
2013-09-05 19:39:52 -07:00
Mike Magruder 69f86175d0 Fix segfault when debugger attempts to set breakpoints
I'm seeing a steady stream of core files from dev boxes with faults under TranslatorX64::addDbgGuards(). Inspecting some of the cores shows that we have a SrcKey with a FuncId which maps to a null Func*. This can happen if a Func is destroyed. Add a function to determine if a FuncId is valid, and use that to skip consideration of SrcKey's which are invalid.

Differential Revision: D954427
2013-09-05 19:39:51 -07:00
bsimmers 6d081ca668 Rename vm/jit/trace.h to vm/jit/ir-trace.h to match the class name
Differential Revision: D954132
2013-09-05 19:39:51 -07:00
bsimmers 52d35f2caf Document the H location code
Differential Revision: D953650
2013-09-05 19:39:51 -07:00
Owen Yamauchi 820feff92c Move emitCall and surprise-flags checking
This is a pretty small thing, but better this way than as part of a
bigger diff.

One interesting thing here is that I'm now having to pass a FixupMap
into one of these stateless helpers, which raises the question of how,
in general, we're going to deal with helpers like this that need to
modify translator metadata (like the fixup map, SrcDB, debug info, ...).

I'm also cheating a bit inside emitCall, grabbing the global tx64
instance to possibly fetch a native trampoline. This is part of the same
problem: how can these stateless helpers cleanly affect global
translator state?

In this particular instance, it would have been easy to make the
fixup-map calls from the emitCheckSurpriseFlagsEnter callsites instead,
but I was uncomfortable with separating the actual assembly call from
the corresponding fixup-map entry.

I also opted to pass CodeBlocks into emitCheckSurpriseFlagsEnter,
instead of Asms, since it made the surrounding code cleaner.

Differential Revision: D954120
2013-09-05 19:39:51 -07:00
Owen Yamauchi 7234c59593 Make X64Assembler short-lived
This is a wide-ranging refactor. We should not have long-lived (i.e.
member) X64Assemblers anymore.

A couple of these changes are non-mechanical, and I'll point them out in
inline comments.

There are a couple things left to do:

- CodeGenerator still has member assemblers. We'll need to apply similar
  changes there, and it's just a ton of functions. I'm leaving that for
  a separate diff.

- This gets us closer to being able to remove the frontier(), base(),
  etc. member functions from X64Assembler, which will be the forcing
  function to finally separate CodeBlock concerns from assembler
  concerns.

Differential Revision: D950811
2013-09-05 19:39:51 -07:00
Drew Paroski de2863dcd0 Add mapWithKey() and filterWithKey() APIs
This adds mapWithKey() and filterWithKey() APIs to all keyed collections
(Vector, Map, and StableMap). These APIs are similar to map() and filter().
The key difference is that these APIs pass both the key and the value to
the user callback.

Differential Revision: D939972
2013-09-05 19:39:50 -07:00
Sean Cannella b989a0d21a add reporting crashes section to README.md 2013-09-05 15:25:10 -07:00
Sara Golemon 5c7ac5db43 Don't store sweepable Object in SessionRequestData
Data inside Object turns into garbage between
requests when the resource is swept.

Closes #990

Differential Revision: D911041
2013-09-04 00:41:52 -07:00
Herman Venter 4a110d6fd0 DebuggerSerialize now preserves resource class and id of resource objects.
The debugger client obtains objects via serialization from the server and then converts them to text on the client. This is the right design since it gives the IDE a structured object that it can present to users in a summarized format. Unfortunately this presents many problems with objects that do not serialize across process boundaries without loss of information. The way resource objects were serialized caused them to show up as empty objects in the client. This diff adds logic to serialization/deserialization to make resources show up as dummy resources in the client. Serializing those to text gives the information that show up when server to text serialization is used.

Differential Revision: D950605
2013-09-04 00:41:35 -07:00
Herman Venter 53251613cc Instead of simply truncating output from =, give user a chance to continue display.
Display the first 200 characters of output, then put up a prompt and continue if the response is positive.

Differential Revision: D949503
2013-09-04 00:41:34 -07:00
Sean Cannella da0b967a4f decrease ring buffer size to 512KB
- decreases ring buffer size to 512KB to better support calling the JVM from an extension (1 MB causes problems with Java's thread stack size assumptions)

Closes #1015

Differential Revision: D953256
2013-09-04 00:41:34 -07:00
Jordan DeLong 58b2146c17 Delete some dead code in tx64
Differential Revision: D954279
2013-09-04 00:41:34 -07:00
Herman Venter 7a0d2d962e Document set command. Add option to set the cut-off length of the = command. Increase default print level from 3 to 5.
The documentation and help for the set command was pretty useless. Made it convey what is possible. Also added and option for the maximum length allowed by the = command. Increased the print level from 3 to 5 since 3 seems too small for real life debugging examples.

Differential Revision: D953805
2013-09-04 00:41:33 -07:00
Paul Tarjan 07606e522d update timeout default for stream_socket_accept
This is the default for zend. I'm using a sentinel value of -1 to indicate we should pull from the ini value

Differential Revision: D943345
2013-09-04 00:41:33 -07:00
Rachel Kroll 50cb41ce4d More tests
Test coverage
Compression, decompression on the fly, adding directories, mmap flavor

Differential Revision: D953688
2013-09-04 00:41:32 -07:00
Sean Cannella 981f41325f fix strerror warning on non-Linux
- strerror_r behaves differently on different platforms

Differential Revision: D953722
2013-09-04 00:41:32 -07:00
Jordan DeLong 1e4a4ac458 Move HphpArray::ElmKey to local use site
Helped me know what it was for.

Differential Revision: D952706
2013-09-04 00:41:32 -07:00
Jordan DeLong ec0b02870e Move the helper for StringData::same into a function
I need to use this instead of memcmp now for D938354.  Doing
the function move in a separate diff to perflab independently.

Differential Revision: D943815
2013-09-04 00:41:31 -07:00
Jordan DeLong a60ceb7853 Make ConvCellToStr & friends not consume refcount
And move the specialization logic to the simplifier.

Differential Revision: D944129
2013-09-04 00:41:31 -07:00
Jordan DeLong f728e2ea8c Remove K flag from ConvFooToDbl instructions
This appears to be left over from when they consumed ref
counts.

Differential Revision: D944139
2013-09-04 00:41:30 -07:00
Mike Magruder c940cf6df3 A little cleanup in TraceProfiler
While working on TraceProfiler I kept hitting things that bugged me about the current code: bad names for things, classes with everything public, etc. This diff cleans a bunch of that up. There should be no semantic changes in this diff... yell if you see one.

I've also removed the TraceProfiler feature to serialize the trace with the results, and the function to deserialize the trace and produce results again. It's completely unused. The flag to turn it on was never exposed to PHP, as far back as the original diff, and there are no uses of the deserialize function in any repo.

Differential Revision: D950718
2013-09-04 00:41:30 -07:00
Jordan DeLong e76f3acf7c Quiet emit-time assert for bare $this in closures in non-methods
We appear to be handling bare $this differently in contexts
where it can actually do something, but it doesn't look like it should
matter: at JIT time InitThisLoc turns into nothing in a non-method
anyway.  Static closures and non-static closures in non-methods with
bare $this end up with a different state for
FunctionScope::needsLocalThis, it was unclear how to fix that earlier
in the frontend that so I'm just quieting the assertion here.

Differential Revision: D952951
2013-09-04 00:41:30 -07:00
Herman Venter a8bc09405c Persist debugger client settings that are altered via the set command
The set command can alter the values of some of the settings that are kept in the per user debugger configuration file. However, these settings do not get persisted back into the configuration file. Since the configuration file is affected by other user commands, this seems a tad strange. As we add more user options, I suspect that these options will be more discoverable if they are documented as part of the set command and if they persist in the configuration file.

Differential Revision: D952387
2013-09-04 00:41:29 -07:00
mwilliams 0a7e581df1 Remove unused IsInherited flag
Its never set, and only used in one place.

Differential Revision: D953257
2013-09-04 00:40:52 -07:00
Sara Golemon 13ddbb4ec1 Exclude ext_zend_compat from infotabs when not on linux 2013-09-03 14:08:59 -07:00
Sara Golemon 6031b2986b Exclude generating ext_hhvm stubs for ext_zend_compat on non-linux 2013-09-03 13:00:15 -07:00
Sara Golemon 0262f2497d Forgot to remove runtime_ext_zend default from last commit 2013-09-03 11:59:05 -07:00
Sara Golemon 0cf88af2cb Only build ext_zend_compat (and related extensions) on linux (for now) 2013-09-03 09:50:24 -07:00
Sara Golemon ff726ebb05 Let ext_zend_compat define its own PACKAGE_VERSION 2013-09-03 09:49:52 -07:00
mwilliams 1169ca671a Fix a few issues with type-inference/optimization and CodeErrors
We were doing type inference on Native functions, which ended
up throwing away the return type, resulting in incorrect type annotations,
and bogus CodeError.js warnings.

Similarly, Native methods were treated as abstract (since they have no body),
resulting in CodeError.js warnings if you derived from classes containing
Native methods.

Differential Revision: D951860
2013-09-03 08:02:37 -07:00
Bert Maher 7fee26b724 Remove m_sendEnded assertion in LibEventTransport::sendImpl
We're exiting early in this case anyways.

Differential Revision: D953174
2013-09-03 08:02:37 -07:00
Edwin Smith e573c7386e Update NEWS for Kimchi release
Differential Revision: D952964
2013-09-03 08:02:36 -07:00
Bert Maher 77aa9efb6c Don't try to send data after the response has already been sent
Prevent memory corruption when a fatal/exception during PSP
triggers a flush() after data has already been sent and the transport
is in an invalid state.

Differential Revision: D953102
2013-09-03 08:02:35 -07:00
Edwin Smith 13ae081fa3 Add DequeuePacked and PrependPacked
We only handle a few easy cases for these, but since these
operations renumber and compact elements on Mixed arrays,
there's no point in escalating from packed to mixed; we might
as well do memmove and leave the existing 0..N numbering.

Differential Revision: D945517
2013-09-03 08:02:35 -07:00
Anna Malova cf2f4332c8 Fixed bug #53319
Fixed bug #53319 (strip_tags() may strip '<br />' incorrectly)

Differential Revision: D951187
2013-09-03 08:02:34 -07:00
Jordan DeLong f1b204d42b Remove the EnableMemoryManager runtime option
Does anyone want this?

Differential Revision: D932380
2013-09-03 08:02:34 -07:00
Drew Paroski 40a9386a3f Fix HHVM command line parsing
At present, there are some corner cases where hhvm doesn't parse command
line arguments properly. For example, doing "hhvm foo.php -u" causes a
'required argument missing' error even though "-u" is an argument intended
for the PHP application.

This diff fixes the problem by doing a manual pass over the args ahead of
time before invoking the boost command line parser. This seems to be the
only reliable way to prevent the boost command line parser from choking on
args intended for the PHP application.

Differential Revision: D952180
2013-09-03 08:02:33 -07:00
Eugene Letuchy a38c58de96 easy: adding T_TRAIT and T_TRAIT_C constants
The constants were undefined, but are necessary for parity
with Zend and for the internal consistency of `token_get_all` and
`token_name`.

Differential Revision: D952502
2013-09-03 08:02:33 -07:00
Drew Paroski c5e9e0a652 Fix bugs with invokeFunc() and invokeFuncFew(), and other cleanup
This diff fixes some bugs with invokeFunc() and invokeFuncFew(), it removes
some dead code, and it converts more places to use cellDup() instead of
tvDup().

invokeFunc() had a bug where the VM stack did not get cleaned up properly
when a warning is raised and the user error handler threw an exception.
This diff adds a catch clause that will perform the appropriate cleanup and
then rethrow the exception.

invokeFuncFew() had a bug where in some cases it would pass a parameter by
reference when the callee required that the parameter be passed by value.
This was happening because TypedValues that were KindOfRef would get copied
onto the VM stack using operator=, and nothing was checking whether the
callee required the parameter to be passed by value. This diff fixes the
issue by reworking invokeFuncFew() and callers of invokeFuncFew().

Differential Revision: D949251
2013-09-03 08:02:33 -07:00
Drew Paroski 783cad3f46 Update NEWS
Differential Revision: D949307
2013-09-03 08:02:32 -07:00
Dario Russi 5bb49bdcb9 protect #define with an #ifndef
Getting strange compiler error and thus protecteing definition in header

Differential Revision: D951881
2013-09-03 08:02:32 -07:00
Stephen Chen 06994a542b Add counters in hhvm to track # of requests killed due to timeout or exceed memory
Right now these manifest themselves just as fatal. I think it then gets pumped
to log view. We don't do a good job monitoring these. Add counters so we can
track them better.

Differential Revision: D949107
2013-09-03 08:02:32 -07:00
Rachel Kroll 92a4af22cd Handle exception messages which are std::string, too
Add support for Exception(std::string)

Differential Revision: D950763
2013-09-03 08:02:31 -07:00
Joel Marcey 9c018aced3 We need to stop boost from trying to guess command line options
Currently boost is guessing at command line options. We need to stop this so we can use --debug for phpunit and not get "Error in command line: option '--debug' is ambiguous and matches" errors from boost.

Differential Revision: D951632
2013-09-03 08:02:31 -07:00
Dario Russi baedb0fc6e Abstract "index to byte" computation out of LdElem and StElem instructions
Moved the shift to compute the position size in bytes out of the instruction LdElem and StElem. Leads to better optimizations

Differential Revision: D949770
2013-09-03 08:02:31 -07:00
mwilliams dc6b199633 Fix nemo warnings for 'resource' and 'callable' typehints
Noticed these showing up because some resource type hints
were added to systemlib.php

Differential Revision: D951170
2013-09-03 08:02:30 -07:00
javer c9975fc184 fix register_shutdown in session_set_save_handler
Do not register automatically session shutdown function when
session_set_save_handler called in PHP <5.4 style.
PHP Manual: Note we additionally register the shutdown function
session_write_close() using register_shutdown_function() under PHP less
than 5.4.0. This is generally advised when registering objects as
session save handlers under PHP less than 5.4.0.

Closes #1001

Differential Revision: D949388
2013-09-03 08:02:30 -07:00
Sara Golemon ed8774975e Restore licenses incorrectly mangled on last push
Update license.php so that doesn't happen again.
Add new ext_hhvm files to .gitignore
2013-08-30 20:57:45 -07:00
Alok Menghrajani 5fa62cce63 Add XHPChild interface, an interface compatible with arrays, strings, ints and doubles.
We currently don't have a way to type XHP's {} operator (i.e. to type $foo in
function ($foo) {
  return <div>{$foo}</div>;
}

An XHPChild interface should solve this issue by having a type which is compatible with arrays, strings,
ints and doubles. We can then modify www to have :x:base implement XHPChild.

To me, this seems like the right step to get rid of the Xhp special casing.

Differential Revision: D886565
2013-08-30 16:04:02 -07:00
Sara Golemon c7a75572f9 Convert SessionHandler class to Systemlib based class
Pretty basic re-wrapping

Differential Revision: D947279
2013-08-30 16:04:02 -07:00
Sara Golemon 512ecad7cb Convert ext_hash function/methods to use new HNI bindings
Delete hash.idl.json.
Implement extension in systemlib (plus native funcs).
This makes ext_hash.ext_hhvm.cpp a noop.

Differential Revision: D940558
2013-08-30 16:04:01 -07:00
Sara Golemon 9effdc0172 Add "native" functions for use in Systemlib
<?hh
  class Foo {
    <<__Native>>
    public function bar(int $baz) : string;

    <<__Native>>
    public static function bling(mixed $blong) : double;
  }

  <<__Native>>
  function blong(string $a, stdClass $b) : void;

  <<__Native("ActRec")>>
  function zorb(int $foo, string $bar): float;

Hooks internal functions:

  String HHVM_METHOD(Foo, bar, int64_t bar) { ... }
  double HHVM_STATIC_METHOD(Foo, bling, CVarRef blong) { ... }
  void HHVM_FUNCTION(blong, CStrRef a, CObjRef b) { ... }
  TypedValue* HHVM_FN(zorb)(ActRec* ar) { ... }

When registered during Extension::moduleLoad() with:

  HHVM_ME(Foo, bar)
  HHVM_STATIC_ME(Foo, bling)
  HHVM_FE(blong)
  HHVM_FE(zorb)

Differential Revision: D922477
2013-08-30 16:04:01 -07:00
Jordan DeLong eceefe5cc4 Devirtualize APC
We have a now-unnecessary abstract base class, so I removed
it.

Differential Revision: D937419
2013-08-30 16:03:59 -07:00
Guilherme Ottoni 64e159b195 Unbreak the build
A minor last-minute change made a variable only used in an assert.

Differential Revision: D950812
2013-08-30 16:03:59 -07:00
Guilherme Ottoni 6dc3c495d2 Add inlining support for profile-guided region selection
In PGO mode, we were punting when the profiling translation had an
inlined call.  Properly supporting inlining was not difficult, but it
required the profile data to keep a region instead of a block for each
profiling translation.

Differential Revision: D944792
2013-08-30 16:03:58 -07:00
Rachel Kroll e449e62625 Somehow, these files were landed despite abandoning the previous diff
Remove files which have no business being in the tree

CI infrastructure was broken... 'arc unit' passes now...

Differential Revision: D950218
2013-08-30 16:03:58 -07:00
Mike Magruder 26b6ce8bb4 Comments and minor cleanup around thread modes and blocking in the debugger.
Added comments and did a tiny bit of cleanup to help understand a bug we currently have with multiple threads hitting breakpoints. Mostly comments and log changes. Any other changes should cause no semantic difference, and are for clarity only.

Differential Revision: D943943
2013-08-30 16:03:57 -07:00
Mike Magruder bd50a818a6 Moar debugger proxy loggin
Add a little more logging to the proxy, for error cases where the proxy declares a protocol violation on the part of the client and disconnects.

Differential Revision: D947864
2013-08-30 16:03:57 -07:00
Paul Tarjan c2695a2985 Zend compatitblility layer
In order to support existing Zend extensions, I'm introducting a source compatitblility layer. Since the extensions are all built around macros, the plan is just to redefine them to work on HHVM internals intead of Zend internals.

I've implemented the most common ones I've seen so far. The plan is to import all the builtin extensions from zend that we currently don't support and use them as a coverage test. So far, this diff includes calendar.

Differential Revision: D938776
2013-08-30 16:03:50 -07:00
Owen Yamauchi 535ae43597 Attempt to bring some sanity to destruction of extension classes
I opened this can of worms while trying to devirtualize ObjectData, and
trying to understand how objects get destructed. It turned out that
every ObjectData and ResourceData subclass was defining its own operator
delete via several layers of macros, and they all did the same thing.

I deleted the one for ObjectData and let everything be handled by the
definition of operator delete in ObjectData itself. ResourceData makes
this harder: given a ResourceData*, we don't have quite enough
information handy to know how big its dynamic type is, so we're still
using the macro-generated override in every ResourceData derived class.

This more closely reflects reality, since ResourceData and ObjectData
are separate class hierarchies now.

Differential Revision: D943826
2013-08-30 10:15:58 -07:00
Andrei Alexandrescu 5f4a193da8 Use /usr/bin/objdump instead of $PATH-found objdump for disassembly
On some machines (such as mine or Drew's), `which objdump` finds /usr/local/bin/objdump, which in turn has version 2.21.1. That makes hphp/util/test/asm.cpp fail due to a different hexadecimal constant formatting convention than the one we expect. Fortunately, /usr/bin/objdump is still 2.17.50.0.6-6.el5 on said machines, which is what works. So this hardcodes that path at least as a stopgap until we figure a better solution. Long-term we should plop a sanctioned objdump version in ~engshare.

Differential Revision: D946553
2013-08-30 10:15:58 -07:00
javer 36a4f6e787 Fix ArrayIterator constructor zend compatibility
Flatten ArrayIterator/ArrayObject when initializing them with
other array wrappers to produce arrays from respective getArrayCopy()
methods

Closes #1000

Differential Revision: D949379
2013-08-30 10:15:57 -07:00
Rachel Kroll 45805950b2 TextUtils for future use in FileCache
String manipulation stuff to replace scary code in FileCache

Differential Revision: D949861
2013-08-30 10:15:57 -07:00
Mirek Klimos c1f5f8b2fc Revision of unit tests for async functions
Tests for async functions were originally just modified tests for
generators. The implementation will be changing soon (eager execution,
AsyncFunctionWaitHandle) and the test will be no longer sufficient.
These modifications are mostly based on problems I encountered while
working on optimizations.

Differential Revision: D943736
2013-08-30 10:15:56 -07:00
mwilliams fbec785f7d Fix crash in compactMergeInfo
There was a race in defClass that could result in
a defClass on a different thread succeeding, before the original
had added the new Class to the NamedEntity's clsList. That could
result in a crash in compactMergeInfo.

Differential Revision: D949580
2013-08-30 10:15:56 -07:00
Jordan DeLong d911c580de Revert "Revert "g++-4.8.1""
This reverts commit f72f602552b261a7cb0d5932cf17a950cfeaef81.

Differential Revision: D947694
2013-08-30 10:15:55 -07:00
Owen Yamauchi 45de75013a Make CodeBlock's interface look like X64Assembler
Purely mechanical. This is going to make an upcoming refactor a little
bit less painful.  Also important: removing the friending of
X64Assembler so the protected members are actually protected.

Differential Revision: D949434
2013-08-29 11:58:48 -07:00
Sean Cannella 980a6762cc Refactor GetNamedEntity (produce read-only version)
- GetNamedEntity always creates an entry into the table, we should not do this for dynamic input

Differential Revision: D938245
2013-08-29 11:58:47 -07:00
Kristaps Kaupe a5c13343ef fixes for issues encountered in extension dev
We are now investigating HipHop, but for that we need to port our
existing PHP extensions. I had to change two small things in hiphop
code, to be able to compile it together with one of our extensions. I
think these changes could be useful not only for us.

1) Renamed macro "field_type" to "hphp_field_type", because it was
making conflicts with mysqlpp library, which have public method
"field_type" in some class. It is pretty generic name, so I believe, it
could make also problems with other third party libraries in future.

2) At some moment I started to get error messages "error: 'size' is not
a member template function" in hiphop, not our code. Don't know exactly
why they started to appear, but after some googling I found
(http://stackoverflow.com/questions/10671406/c-confusing-attribute-name-for-member-template)
that this is known GCC bug and workaround is very simple - put
parenthesis around "old->size" in hphp/runtime/vm/tread-hash-map.h:203.

Closes #996

Differential Revision: D947510
2013-08-29 11:58:47 -07:00
Anna Malova bc64e974d5 Fixed bug #46578
Fixed problem with single quote inside comment

Differential Revision: D947836
2013-08-29 11:58:46 -07:00
Sean Cannella f98d71d6f0 instanceof needs to denormalize name
- iopInstanceOf needs to denormalize input

Closes #963

Differential Revision: D945675
2013-08-29 11:58:46 -07:00
Jordan DeLong 3ec265c56e Add a bit more commentary on fcallArrayHelper
This was asked for in review, but it was easier to do on top
of the refactoring changes.

Differential Revision: D942880
2013-08-29 11:58:45 -07:00
Jordan DeLong 7dfffa6b3f Port unique stubs to use new assembler API
Not much of the old API was left.  Done in separate diff for
reviewability.  Also fixed some incorrect comments in the
funcPrologueRedispatch stub.

Differential Revision: D942878
2013-08-29 11:58:45 -07:00
Jordan DeLong 5edf20b293 Split unique long lived shared stubs generation out of tx64
Translator modularization.  Mostly mechanical code motion,
with addition of some documentation and better logging (disasm
support, etc).  It's possible that the set of stubs for ARM vs x64
might not be exactly the same eventually, but it might, so for now
this is layed out with the assumption that a future
unique-stubs-arm.cpp will populate the same list of stubs.  (I also
tried drawing the line on a per 'stub group' basis, but too many stubs
have tricks about layout and it seemed hard to predict whether that
would commonize anything other than the function call loop, so we can
do it later as needed.)  Also rename the JIT::CodeGenHelpersX64
namespace to JIT::X64.

Differential Revision: D942874
2013-08-29 11:58:45 -07:00
Sean Cannella b51f5e8c76 enable building against libmemcached 1.0.8
libmemcached 1.0.8 still allows access to the fields we need
on the old structures (memcache_server_st) so allow building against
that [since it appears to be what Ubuntu 13.0.4 uses for
libmemcached-dev.]

Differential Revision: D947880
2013-08-29 11:58:44 -07:00
bsimmers e282644ddf Add inlining support to the tracelet region selector
The tracelet region selector now supports creating regions with
inlined calls. When it sees an FCall with a known callee, it invokes a new
instance of the tracelet region selector on the callee. The callee is evaluated
using the same cost metric as Translator::analyze. If it passes, the callee is
inlined for real, which allows creation of longer tracelets based on the return
value from the callee.

Differential Revision: D909359
2013-08-29 11:58:44 -07:00
bsimmers c9bc3139d6 More detailed logging when afdt fails to connect
This test has been failing sporadically and I'd like to see
why.

Differential Revision: D947587
2013-08-29 11:58:43 -07:00
Owen Yamauchi 63b12a4461 Refactor service requests
Service requests are part of the translator infrastructure and are
entirely[1] platform-agnostic. I factored out the definitions and the
argument-packing code into their own file.

Then I moved emitServiceReqWork into CodeGenHelpersX64. It was a little
difficult to untangle, since it had several direct uses of tx64 state. I
tried moving emitBindCall and friends too, but it got a lot more
difficult. I'll do that in another diff, to keep this one manageable.

I put this new header file in HPHP::JIT, so I had to introduce some
JIT:: line-noise elsewhere, but this is actually the lesser of two
evils. If I put it in HPHP::Transl, there ends up being Transl::
line-noise in a lot more places. Since JIT is where we're ultimately
headed to (right?), this seemed better.

[1] They're not entirely platform-agnostic, but they should be. Right
now they depend on the x64-specific ConditionCode enum. We use a very
limited set of x64 condition codes in this context, so we should be able
to define a platform-agnostic set of condition codes (a subset of the
intersection of ARM and x64 condition codes) and use it here. I'm
punting on that for now, though.

Differential Revision: D933753
2013-08-29 11:58:43 -07:00
Herman Venter cc4c70398a Remove dead catch blocks.
evalPHPDebugger catches and suppresses all exceptions except debugger exceptions. Hence the catch clauses that follow its only call site are dead code, except for the catch all, which seems just wrong to me since it suppresses Debugger exceptions that are explicitly propagated by evalPHPDebugger.

Differential Revision: D945652
2013-08-29 11:58:43 -07:00
Rachel Kroll 2eac31d703 Correctness fixes
Clean up #includes, namespace/using, iterators, magic numbers

Differential Revision: D947659
2013-08-29 11:58:42 -07:00
Bert Maher d03724a749 Align global slabs to 16 bytes
Believed to fix a crash in prod caused by using movdqa to
access globals aligned to 8 bytes instead of 16.

Differential Revision: D947649
2013-08-29 11:58:42 -07:00
Herman Venter 5e215dbca2 $_ not cleared but still printed after exception
The code to print out the result of the expression following the = command has moved from inside the resulting eval block, to outside it in the debugger code itself. Hence, if the eval block fails, the value of $_ now prints out and this is confusion because it is the value that a previous = command put in there. With this change the eval block first unsets $_, so that the subsequent print value code will do nothing in the case of a failure.

Differential Revision: D944120
2013-08-29 11:58:42 -07:00
bsimmers b6081d95cc Disable flaky zend test, trim down test with external dependencies
Differential Revision: D946456
2013-08-29 11:58:41 -07:00
Sean Cannella 9c19e02263 update dev build of composer
update composer which has timed out (failing unit tests)

Differential Revision: D947366
2013-08-29 11:58:40 -07:00
Paul Tarjan e18da2a719 increase slowtimer threshold
I sometimes see failing test runs because curl is slow on a box.

Lets make it the same timeout as the script itself.

Differential Revision: D945165
2013-08-29 11:58:40 -07:00
mwilliams 6a87dbf1e5 Revert "g++-4.8.1"
This reverts commit 7d94e20daede9ab6fa1d3bdc6f0a03477a631efc.

Some tests are breaking in the opt build.

Differential Revision: D946629
2013-08-29 11:58:40 -07:00
mwilliams 4accc0496c Fix a crash in Unit::compactMergeInfo
If redoHoistable is set, at least one defClass failed,
so we can't compact the unit.

This should prevent crashes - but something must have gone wrong
to get into this state. An AttrUnique class should never fail
to be defined.

Differential Revision: D946531
2013-08-29 11:58:39 -07:00
Emil Hesslow a62bf121a5 Fix clone of SplPriorityQueue
Clone the underlying _SplPriorityQueueHeap object when someone clones a SplPriorityQueue object

Closes #984

Differential Revision: D942743
2013-08-29 11:58:39 -07:00
bsimmers a66d7818ce Disable fread_socket_variation1.php
I've seen it fail on a few completely unrelated diffs

Differential Revision: D945745
2013-08-29 11:58:39 -07:00
Jordan DeLong 42f7e857f6 Move fCallArrayHelper to an asm helper stub
fCallArrayhelper smashes its return address, leading to
return branch mispredictions until we return enough times to get back
on track.  Rewrite it as an asm stub so it can make a tail jump and
pop the proper return ip into the ActRec.

Differential Revision: D941930
2013-08-29 11:58:38 -07:00
Jordan DeLong 9f08515ad4 Don't leave out AttrPhpLeafFn on account of FCallArray
FCallArray does a stack overflow check as part of its
"mini-prologue", so we can still consider functions that use it leaf
functions.

Differential Revision: D940120
2013-08-29 11:58:38 -07:00
Mike Magruder 84d1d995d0 Fix bugs when multiple threads hit the same breakpoint
The function blockUntilOwn() was not actually blocking threads before letting them into processInterrupt(), which allowed multiple threads hitting breakpoints to process their interrupts and communicate with the client, which is bad.

Also fixed an issue where interrupts processed during an eval would result in erasing the current thread's 'lock' on processing interrupts, resulting in the same issue.

Differential Revision: D945203
2013-08-29 11:58:37 -07:00
Sean Cannella 2dcf721cea fix namespace bugs in ext_class/ext_reflection
- ext_* functions that call Unit::lookupClass were not correctly
handling denormalized names (ex. \FooNS\Bar), this adds a wrapper for
this pattern and calling it.
- ReflectionClass::subclassOf should be using f_is_subclass_of

Closes #827

Differential Revision: D945363
2013-08-29 11:58:37 -07:00
mwilliams da668c3500 g++-4.8.1
Switch to g++-4.8.1

Differential Revision: D935591
2013-08-29 11:58:36 -07:00
Markus Staab eaba93f75b adjust ArrayIterator internals for zend parity
HHVM's current implementation promotes internal state to possible
subclasses.

This is meant as preparation to support RegexIterator in a separate
commit, because the Zend tests rely heavily on the internal var-dump
representation of ArrayIterator.

Closes #989

Differential Revision: D943461
2013-08-29 11:58:36 -07:00
Daniel Sloof ed5a9dc09f make simplexml xpath return original objects
Currently, xpath just creates new elements. This means that any
modification done to the return object will not change its original
parent.

xpath can also traverse -up- the hierarchical node tree, so we cannot
just recursively go through children to find a matching node. this is
why an additional m_root was introduced, to keep track of the root node
of the current tree.

Closes #986

Differential Revision: D943404
2013-08-29 11:58:36 -07:00
bsimmers 77dea1bdd0 Temporarily remove Iterable's function declarations
D923036 added these but we're not quite ready. Take them out for now.

Differential Revision: D944660
2013-08-29 11:58:35 -07:00
bsimmers d4dbe54e59 Fix region_tracelet test
The tracelet region selector was relaxing a guard that the normal
translator wasn't, exposing a bug in the register allocator: when a load
instruction has a label we care about its type, so we can't assign it to an xmm
register. We really shouldn't be guarding on this load at all, but that can be
fixed in a separate diff.

Differential Revision: D944937
2013-08-29 11:58:35 -07:00
Jordan DeLong 4b8304f07a Remove try/catch in conv{Obj,Res}ToStrHelper
We have a catch trace that does a SpillStack for both of
these helpers.  Incidentally, zend raises a fatal if you try to throw
in this situation.

Differential Revision: D944079
2013-08-29 11:58:34 -07:00
Jordan DeLong 3a2194c88d Implement StringData::initAttach in terms of initCopy
This seems reasonable.

Differential Revision: D938745
2013-08-29 11:58:34 -07:00
Rachel Kroll fe9d608898 Test a few paths through FileCache
Start testing FileCache

Differential Revision: D944350
2013-08-29 11:58:33 -07:00
Jordan DeLong dd8a4fd6b7 Some cleanup on HPHP::CstrBuffer
Don't use DECLARE_BOOST_TYPES (use make_shared where
appropriate).  Delete the broken (double-free) default copy
constructor and copy assignment operator.  Also document some things
because a few points are more subtle than they seemed (unlike
StringBuffer, most functions have a precondition that the buffer is
valid, and the filename constructor does not report errors).

Differential Revision: D931752
2013-08-29 11:58:33 -07:00
Dario Russi 55f3a63d54 inline vector/pair get and vector set
Define new OpCodes to allow code generation for vector style get and set

Differential Revision: D905624
2013-08-29 11:58:33 -07:00
Paul Tarjan 61543666b9 fix test paths and import extra files to bad
@WizKid has been doing a few diffs on HHVM recently and he noticed that the path of the errors didn't match zend. This is totally right and I was being dumb trying to emulate the old perl script for our paths. Instead we should just match %s.

I also noticed you can't just run the bad tests from their directory since sometimes they need an `.inc` file. We should just duplicate those files in there so you can run the bad tests directly.

Differential Revision: D943288
2013-08-29 11:58:32 -07:00
Alok Menghrajani 7202c3d569 Rename the magic "__resource" class to "resource"
www engineers would like to be able to provide the type for code which
takes a resource as input. This simple change is a first step in the right direction.

In the future, we might want to provide a way to specific the exact type of resource
(e.g. PlainFile vs CurlHandle).

Differential Revision: D873115
2013-08-29 11:58:28 -07:00
huzhiguang d6f4be7d07 Fix libevent keepalive memery leak
Closes #997
2013-08-29 10:09:15 -07:00
Sara Golemon 8f6c166d5b Update folly 2013-08-29 09:58:34 -07:00
Sara Golemon 2960debf8f Hide composer expiration warning 2013-08-28 16:30:28 -07:00
Sara Golemon 825db91e22 Update Folly 2013-08-28 15:12:23 -07:00
Jordan DeLong 981c510eb2 Delete the rest of the litstr comparison ops
I want to remove StackStringData, and these were some of the
uses remaining.

Differential Revision: D935951
2013-08-27 11:58:31 -07:00
Jordan DeLong 64ca1fc194 Clean up StringBuffer a bit
Privatize several public functions, remove some redundant
functions, make some things non-members (appendJSONEscape), remove
DECLARE_BOOST_TYPES, and document contracts; also some gratuitous
style changes.  I was initially planning to make it include the null
in its capacity, but since capacity is not exposed anywhere I think
it's fine as is.  (And eventually we don't want to require the null
when handing off to String---only when people call data()---but that
is a separate project.)

Differential Revision: D931746
2013-08-27 11:58:31 -07:00
bsimmers 134a0d79bb Support specialized types in the tracelet region selector
Most of the hard work to support specialized types was getting guard
relaxation working, so this diff is pretty straightforward. The only big change
is collapsing GuardCls and GuardArrayKind back into GuardLoc. If that turns out
to be a noticeable perf regression I can investigate other options.

Differential Revision: D936145
2013-08-27 11:58:30 -07:00
bsimmers 599a2cacd3 Make hhir guard relaxation less conservative
This diff expands guard relaxation to relax all eligible
guards, not just guards for values that are never read. Specialized
types are still not supported yet; the tracelet region selector drops
all specializations.

Differential Revision: D934157
2013-08-27 11:58:30 -07:00
Edwin Smith 21795c5415 Move util/vixl up one level
Giving each lib/exe build target its own toplevel dir.

Differential Revision: D943470
2013-08-27 11:58:30 -07:00
Sara Golemon ea0a7f6636 Get rid of errant double-license 2013-08-27 11:58:30 -07:00
Paul Bissonnette b913a5d9a5 Generalized Inlining
Generalizing inlining to work with more complex functions.

Differential Revision: D898434
2013-08-27 11:58:30 -07:00
Edwin Smith 4a0c336da6 Move util/parser up one level.
It defines its own library, make it a peer with other libs.

Differential Revision: D943071
2013-08-27 11:58:30 -07:00
Joel Marcey 849db6b623 Implement ReflectionMethod::setAccessible()
The unit tests for Composer require a call to ReflectionMethod::setAccessible(). This implements that method.

Differential Revision: D939166
2013-08-27 11:58:29 -07:00
Edwin Smith 4c638d419e Move util/neo up one level
It defines its own library, remove the unnecessary nesting.

Differential Revision: D943068
2013-08-27 11:58:29 -07:00
Guilherme Ottoni 66a48e178e Fix get_class_methods() to include trait methods
get_class_methods() was not including methods that came from traits.
This diff changes get_class_methods() to look at the Class' method
table, instead of the PreClass.  With this approach, we could avoid
traversing the inheritance hierarchy.  However, that changes the order
of the methods in the resulting array.  So, in order to preserve the
order, this diff still traverses the inheritance hierarchy, and
methods are added to the array when visiting the class that declared
them.

This modification changed the order of methods for some "quick" tests
with classes derived from builtin classes.  However, hhvm was not
matching Zend on these tests already, so I updated them.

Differential Revision: D940214
2013-08-27 11:58:29 -07:00
Owen Yamauchi 88cd96db87 Devirtualize ObjectData, part 1
The C++ vtable pointers and the m_cls pointers in ObjectData are
redundant for C++ extension classes; they both indicate the ObjectData's
dynamic type.

This diff gives ObjectData the same treatment that the ArrayData
hierarchy got, replacing virtual functions with manual dispatch based on
attributes and m_cls. We can't do direct comparison against m_cls,
because of inheritance, except when we know inheritance is not in the
picture.

The vtable isn't gone yet, because I need to do something about C++
destructors, which still require virtual dispatch. That's going to
require a lot of grunt work, so I wanted to put this diff up to keep
that stuff separate.

I did, however, make ~ObjectData non-virtual and try to compile, to
flush out all the dynamic_casts of ObjectData.

- The type-casting functions and clone() are pretty straightforward. The
  only trick is that specialized clone() functions now have to call
  cloneImpl() instead of the base class' clone(), otherwise infinite
  recursion. I added an ObjectData attribute to indicate whether clone()
  is special.

- t___{sleep,wakeup} didn't even need to be virtual, it turns out.
  ObjectData's implementation goes through the normal PHP-method lookup
  path, which effectively does virtual dispatch and routes us to any
  specialized implementations anyway.

Differential Revision: D940852
2013-08-27 11:58:28 -07:00
Edwin Smith fd881ac637 Rename _ to - in hphp/util
One more step in the renaming arc.
Depends on D925182

Differential Revision: D927227
2013-08-27 11:58:28 -07:00
Sean Cannella 84e61d1f94 Merge pull request #994 from staabm/apt_fast
speedup travis ci build using apt-fast and paralleled downloads
2013-08-27 11:16:19 -07:00
Markus Staab 0b2dfdf449 run all downloads in background and in parallel 2013-08-27 14:31:12 +02:00
Markus Staab 4add8586c5 use apt-fast instead of apt-get to speedup build 2013-08-27 12:40:07 +02:00
Edwin Smith 2dea04cf9b Use StringData::same() in a few more places to reuse code.
Now that same() has a faster comparison loop than memcmp,
use it in a couple more places.

Differential Revision: D942902
2013-08-26 09:21:41 -07:00
Bert Maher a24fbde50b Refactoring member-operations so each kind of base has its own function
I liked the results of some cleanup of SetNewElem, so I
decided to extend it to many of the other Elem* functions in
member-operations.h.  This diff really just moves code around to make
it easier to experiment with in the future.

Differential Revision: D932351
2013-08-26 09:21:40 -07:00
Edwin Smith 15dc5b0221 Use "Packed" as the term for vector-like arrays.
The term Vector is getting too overloaded in our codebase.  Rename
vector-like array kinds to "packed" instead.

Differential Revision: D935245
2013-08-26 09:21:40 -07:00
Emil Hesslow 94e49318e4 Handle $a[] = 1
- This is how Zend does it. If $index is null treat it as no $index at all

Differential Revision: D943043
2013-08-26 09:21:39 -07:00
Emil Hesslow 1d660802c2 Add CachingIterator
- Implement CachingIterator
- I ran the idl/sysdoc.php script on my file but it didn't do anything to it
- I started with https://github.com/php/php-src/blob/master/ext/spl/internal/cachingiterator.inc and then added everything that it was missing
- Some of the documentation at http://www.php.net/manual/en/class.cachingiterator.php is strange. All the offset function say that they take string arguments. But the class implements ArrayAccess which specify the arguments as mixed. So I went with mixed because otherwise I got a fatal
- I moved over all bad tests that are now passing
- The rest of the bad tests that test CachingIterator are passing too. It is just that error messages are different so I can't move them to good

Differential Revision: D942889
2013-08-26 09:21:39 -07:00
Drew Paroski f3da1ade07 Fix gettype() for resources
Differential Revision: D941144
2013-08-26 09:21:38 -07:00
Edwin Smith 47d8ee5298 Remove Array::addLval() methods, use lvalAt() instead.
The AddLval methods were fairly cold, so reimplement them in
terms of lval(), but preserve the assert that ensures the keys
being added do not already exist.  This reduces the number
of kind-specific methods we need to implement.

Added Array::setWithRef(key,value) to capture a common use
case for lvalAt().  Later this can implemented more efficiently
as a virtual method in ArrayData subclasses.

Differential Revision: D937227
2013-08-26 09:21:38 -07:00
Jordan DeLong 09d0dbf15c Fix nemo issue (BadArgumentType) for type aliases to non-objects
At call sites, it was complaining because it thought an alias
parameter must be a name of an object.  Also make a function less
nested.

Differential Revision: D942157
2013-08-26 09:21:37 -07:00
Jordan DeLong 7cc3516b8f Change StringSlice to take a uint32_t instead of an int
StringSlice{foo, bar} where bar is uint32_t produces an error
(in 4.7.1, 4.6 doesn't have this part of C++11 correct yet).

Differential Revision: D938436
2013-08-26 09:21:37 -07:00
Jordan DeLong 43c7e09579 Fix type aliases for function types
They were just broken.  Right now, even evaluating a unit
that is declaring one just leads to attempting to autoload the empty
string as a type alias (since it thinks the type alias was
KindOfObject).  Changes them so they work just like normal <?hh
function typehints (currently unchecked).

Differential Revision: D942768
2013-08-26 09:21:36 -07:00
Drew Paroski e0775ce8b6 Fix list assignment with collection literals
Doing "list($x,$y) = Vector {1,2}" should work. Make it so.

Differential Revision: D940987
2013-08-26 09:21:36 -07:00
Drew Paroski 9c2223e9c7 Support "tuple(..)" in initializer expressions
Differential Revision: D940814
2013-08-26 09:21:35 -07:00
Drew Paroski ed680695ea Improve 'string key not present' exception message for collections
At present the 'string key not present' exception message can be misleading
when the string key is truncated (which happens when the string key exceeds
20 characters) and this has caused some confusion.

This diff improves the exception message in two ways. First, the string key
will only get truncated when the key exceeds 100 characters. Second, the
exception message will make it clear when the string was truncated by
printing "(truncated)" after the string key.

Differential Revision: D940984
2013-08-26 09:21:13 -07:00
mwilliams 00ec2d1971 Reinstate fb_setprofile
Its the only way we have for reliably testing hard to repro edge
cases (such as timeouts during FunctionEnter/FunctionExit) and I find it
very useful for debugging complex code.

Differential Revision: D941226
2013-08-26 09:21:13 -07:00
Sara Golemon 92641497cc Fix Zend string_crypt() to report failures properly
strdup(crypt_r()) can result in a segfault
if crypt_r() returns null.

Closes #983

Differential Revision: D940753
2013-08-26 09:21:12 -07:00
Mike Magruder bdf3493274 Fix generator-related errors in PHProf output
Fire EventHook::FunctionExit() in the correct places for generators. This was happening during Continuation destruction, which is quite a while after we exit the continuation, and causing double notifications for continuation exits. Also fire the event when unwinding out of a generator, since that one was missing.

Differential Revision: D939893
2013-08-26 09:21:11 -07:00
Sean Cannella 60d247d450 HHVM should compile with libmemcached 1.0.9+
libmemcached 1.0.8 broke the memcache/memcached extensions. It
is also missing some API support we need, so this should unbreak us as
of 1.0.9+. 1.0.8 plain won't work but earlier and later will.

Closes #934
Closes #973

Differential Revision: D939850
2013-08-26 09:21:10 -07:00
Edwin Smith 3df3ce4f15 Move util/zend (which defines zend.a) up one level.
And rename _ to - while we're at it.

Differential Revision: D925182
2013-08-23 11:24:47 -07:00
Drew Paroski 6d87dee498 Support "(new Vector {..})->method()" style syntax
This diff adds support for calling methods directly on collection literal
expressions (as long as the collection literal is wrapped in parentheses).

Differential Revision: D940562
2013-08-23 09:59:53 -07:00
Sean Cannella 9bdf60c0a9 ReflectionProperty(null,null) should throw
ReflectionProperty constructor should reject nulls

Closes #975

Differential Revision: D939337
2013-08-23 09:59:29 -07:00
Daniel Sloof d2981f6f81 fallback to default separators in number_format
When number_format receives 'null' for one of its separator parameters,
we must pass it back to t_number_format so it can decide whether or not
it should fallback to its default separators.

Currently, when passing NULL to a parameter that is defined as String,
it is implicitly converted to an empty string, and subsequently
str.isNull() will return false.

Instead, we use a Variant with a default string value.

Closes #982

Differential Revision: D940482
2013-08-23 09:59:28 -07:00
Sara Golemon 00908f8be3 Reduce bad error spam on too few arguments
function foo($bar, $baz) { }
  foo();

Currently raises two errors:

  foo() expects exactly 2 parameters, 0 given
  foo() expects exactly 2 parameters, 1 given

Only the first of these is either meaningful or correct.
Stop reporting once we've raised it.

Differential Revision: D939810
2013-08-23 09:59:27 -07:00
Simon Welsh f9d0c1128a use trigger_error in PHP for Redis user errors
- trigger_error is intended for reporting user errors, not
error_log

Closes #970

Differential Revision: D937921
2013-08-23 09:59:27 -07:00
Sean Cannella af07c475f5 move more helpers out of code-gen
Move more stateless platform dependent and agnostic helpers out of
code-gen.cpp

Differential Revision: D936727
2013-08-23 09:59:26 -07:00
Daniel Sloof 7a8c8474ec multiple simplexml fixes
- multiple fixes for simplexml required by magento

Closes #790
Closes #819
Closes #955

Differential Revision: D925428
2013-08-23 09:59:25 -07:00
Mike Magruder 0db30b9e10 Remove some dead profiling code
This profiling path was unused after D894723. Removing it.

Differential Revision: D934477
2013-08-23 09:59:25 -07:00
Markus Staab fe6cfe9fa3 fixed serialize/unserialize for SplObjectStorage
added error handling for bad serialized strings according to zend tests.
We cannot move the actual tests from "bad" to "good" because ATM they
rely on the internal serialized string format of SplObjectStorage, which
is not yet reimplemented.

Closes #969

Differential Revision: D935251
2013-08-23 09:59:24 -07:00
Mirek Klimos fb53e8c8a5 Parser refactorings: onFunction/onMethod/onClosure
We have separate methods for parsing functions and methods
(onFunction/onMethod), which have a lot in common. On the other
hand, onClosure just calls onFunction with a special parameter
that modifies its behavior. Lets make this more consistent and
remove the duplicated code.

Differential Revision: D934034
2013-08-22 12:40:20 -07:00
Edwin Smith 666fa474ff Optimize string same() and hitStringKey()
Most strings used as keys are either small or not shared, where the
data pointers cannot be equal.  Of the rest (shared), most could have
been small.

This diff copies small SharedVariant strings, so they don't refer
back to the SharedVariant, and don't need to be enlisted.  Then,
this changes hitStringKey() to not check data pointers, making it
equivalent to StringData::same().  Lastly, hand-write the comparison
loop in StringData::same() so we compare words at a time, and the
loop can be inlined.

Differential Revision: D937233
2013-08-22 12:40:19 -07:00
Joel Marcey c877f4b737 Implement ReflectionParameter::IsCallable()
The Facebook SDK unit tests fataled because ReflectionParameter::IsCallable() was not implemented. So, this implements it. Now the unit tests pass. Bad zend test now passes!

closes #931

Differential Revision: D938769
2013-08-22 12:40:19 -07:00
bsimmers 5d16068921 Rename VectorTranslator to MInstrTranslator
Vector has become too overloaded in this codebase. MInstrTranslator is
more accurate anyway; we have multiple different types of hhbc opcodes with
immediate vectors that aren't m-instrs.

Differential Revision: D935859
2013-08-22 12:40:18 -07:00
Mirek Klimos fd7f000649 Prerequisites for eager execution of async functions
Here's a few minor changes in emitter that will be needed later for
eager execution of async functions. Just to make the upcoming diff
sipmler.

Differential Revision: D935301
2013-08-22 12:40:17 -07:00
Edwin Smith 6d43cf6ef5 Add DataTypeProfiler
You can use this anywhere to sample the DataTypes at a particular
point in the code, for example calls to JIT helpers.

Differential Revision: D925193
2013-08-22 12:40:17 -07:00
Eric Caruso 07aaeff5ec Improve error message for post-try blocks which are not finally
Currently, hhvm interprets post-try blocks not necessarily
beginning with an actual finally token as finally blocks, and thus
produces an error message to the user telling them finally blocks
are disabled even if they misspelled something, for example.

This moves things so the "finally disabled" message only comes up
if you enter a syntactically valid finally block.

Differential Revision: D918867
2013-08-22 12:40:16 -07:00
Jordan DeLong d5ae3d1bbe Make new stack_overflow test more tolerant
In contbuild it's failing on line 5 instead of 6.

Differential Revision: D937472
2013-08-22 12:40:11 -07:00
Edwin Smith e54b0dc4a9 Do not check for self in assignValHelper.
It should be almost never true, and the assignment code is
already safe for self-assignment.  Note if Variant V == uninit,
then V=V now converts to null, unlike before.  IMHO this is
a bugfix but I don't know that we've seen it in the wild.

Differential Revision: D933229
2013-08-21 09:33:14 -07:00
Edwin Smith 288d4993e2 Remove allocElmFast; its only called in one place.
It used to have two callsites before the vector code landed.

Differential Revision: D932789
2013-08-21 09:33:13 -07:00
Emir Habul 7d03ed4284 hphp: Instance ID for controlled stopping of server
When port-takeover is used, new instance of the process will be started but
something can call stop command for the old task. Given how `localhost:9099/stop?`
can affect hhvm that was just started, I want to limit stop command to be
specific to an instance ID.

This instance ID could be a random number, or container uuid of LXC.

Differential Revision: D932953
2013-08-21 09:33:12 -07:00
mwilliams 9e35396b7f Fix some stack overflow bugs
If re-entry triggers stack overflow, there is no FCall or FCallArray,
so the code to find the pc in REQ_STACK_OVERFLOW would fail. If it
managed to get through there, it would then try to DecRef the contents
of an ActRec, sometimes causing it to DecRef a Func.

In addition, if a "leaf" function resulted in re-entry we didn't
necessarily check the stack.

Differential Revision: D936843
2013-08-21 09:33:12 -07:00
bsimmers 8653894f94 Trim down test/slow/ext_network
It's flaky because it depends on external servers
responding. Remove those bits.

Differential Revision: D935602
2013-08-21 09:33:11 -07:00
mwilliams 4c5adad866 Fix a crash destroying Funcs
Func::destoy needs to block on getting the write lease, so it
can smash the function prolog.

Also, the prolog array in cloned closures is used to redispatch to
the translation corresponding to the clone, since we never enter
such functions via their prolog. Since its not a true prolog, we
shouldn't smash it.

Differential Revision: D933704
2013-08-21 09:33:10 -07:00
Markus Staab d400153b21 move SplObserver tests from bad to good
move basic tests for SplObserver

Closes #968

Differential Revision: D935248
2013-08-21 09:33:10 -07:00
bsimmers 52e16a280c Add basic guard relaxation to hhir
This diff implements basic guard relaxation in hhir. Whenever we read
a local or pop/peek at HhbcTranslator's EvalStack, a DataTypeCategory is
specified. The source of the value is traced back as far as possible, and if we
end up at a guard instruction, the constraint for that guard is updated
appropriately. After IR generation, a pass is run to change the types of these
guard instructions to the least specific type allowed by their constraint. This
is currently only used to eliminate completely unused guards in the tracelet
region selector, so all the guards are either DataTypeGeneric or
DataTypeSpecific.

Differential Revision: D924955
2013-08-21 09:33:10 -07:00
Paul Saab 04b77176fe Fix sockopen_impl with IPv6 addresses
sockopen_impl requires IPv6 addresses be enclosed in brackets.

Differential Revision: D927309
2013-08-21 09:33:09 -07:00
tmulchay b5ae1aab3a Fixing typo in zRevRange function
The zRevRange function argument $withscore was referenced
within the function as $withscores. Changed argument name to $withscores
so they match.

Closes #941

Differential Revision: D934709
2013-08-20 09:04:53 -07:00
bsimmers e63912361a Miscellaneous cleanup
This is all stuff I did while working on guard relaxation
that isn't strictly related to guard relaxation:
- Stop using CheckType with Nullptr.
- Move a bunch of things from ir.cpp to extra-data.cpp and ssa-tmp.cpp.
- Turn DataTypeCategory into an enum class.
- Add folly::FormatValue specializations for JIT::Opcode,
  DataTypeCategory, and any objects with a toString method.
- Kill the Eval.JitCompareHHIR runtime option. Most of the code using
  it is already long gone.
- Add smart::flat_set.
- Clean up MInstrInfo constants, fixing a bug that missed some
  undefined local warnings.
- Assert that the type of IRExtraData subclasses passed to gen()
  matches what the opcode wants.
- Remove unused DontGuardLocal, DontBreakLocal, and DontBreakStack1
  from translator inputs.

Differential Revision: D926849
2013-08-20 09:04:52 -07:00
Mirek Klimos 3682f42d8a Removing unnecessary mapping of var ids on CreateCont.
Since D898769, all locals in generator bodies have the same ids
as in the corresponding 'create generator' methods, so the mapping
between these ids is no longer needed.

Differential Revision: D932354
2013-08-20 09:04:51 -07:00
Sean Cannella a8c26e832b Factor register shuffle algorithm into own module
Factor register shuffle algorithm into own module

Differential Revision: D932183
2013-08-20 09:04:51 -07:00
mwilliams 1cafbeb006 Remove some redundant bool parameters
No longer actually used

Differential Revision: D933388
2013-08-20 09:04:50 -07:00
Bert Maher c01103b732 Update NEWS for release
Updating the NEWS file for our next release.  These were some
highlights that I plucked from the commit log but I'm open to adding
or deleting some.

Differential Revision: D933280
2013-08-20 09:04:50 -07:00
Jordan DeLong 922a1fb454 Remove execute permission from ir.specification
Differential Revision: D932404
2013-08-19 10:15:20 -07:00
Jordan DeLong ffff9c7722 Remove doc/coding_guideline
Outdated and stuff.

Differential Revision: D932395
2013-08-19 10:15:20 -07:00
Jordan DeLong 81c8238c5b Delete doc/runtime.type_system
It's mostly describing hphpc.

Differential Revision: D932386
2013-08-19 10:15:19 -07:00
Mike Magruder 3fea3d93f7 Fix breakpoints on generators
Setting a breakpoint on a generator would work, but it would set it on the function which simply returns the continuation. That's not super-useful, and the intention is to set it on the beginning of the generator. Changed to do that. This change also gets the $continuation off of the function name when printing it at breakpoints.

Differential Revision: D931931
2013-08-19 10:15:19 -07:00
Andrew Gallagher de2fc5ca3b hphp: fix use of has_trivial_destructor
gcc-4.8 and 4.7 aren't consistent about this functions name, so use
boosts version instead (as per D923359).

Differential Revision: D925051
2013-08-19 10:15:19 -07:00
Herman Venter becb0e7784 Color output of = command. Update help. Implement "print r" to accompany "print v" and to provide a way of getting at old print behavior (if the old help text is to be believed).
The = command has recently been changed to use standard debugger serialization rather than to invoke a customizable function, or print_r otherwise. In the process a bug crept in that made the output not colored. This fixes that bug. It also updates the help text to make it clearer that = truncates text. While looking at that I noticed that the help text for the print command suggested that it's output is formatted with print_r. Fixed the text as well, but while I was at it introduced the "print r" flag to make it possible to invoke print_r, analogously to the already existing "print v" command. While adding test cases, I noticed that the truncation logic appears to be broken, so I fixed that as well.

Differential Revision: D931565
2013-08-19 10:15:18 -07:00
Sean Cannella 93e30adfaf SPL + filter extensions should report implemented
- Report that we implement SPL and filter extensions (needed for Drupal)

Closes #946

Differential Revision: D931374
2013-08-19 10:15:18 -07:00
Markus Staab efc12df155 add SplObserver and SplSubject interfaces
- add SplObserver and SplSubject interfaces

Closes #953
Closes #960

Differential Revision: D931324
2013-08-19 10:15:17 -07:00
Drew Paroski ed35cc6304 Update Iterable interface, add toArray() method
This diff adds a toArray() method to the Iterable interface, as well as
adding some other methods that were missing from the interface (map(),
filter(), etc). It also deprecates IterableTrait and KeyedIterableTrait,
introduces LazyIterable and LazyKeyedIterable as replacements, and adds
strict versions of the traits called StrictIterable and StrictKeyedIterable.
Finally, it deprecates the view() method (since I want to introduce a new
method named "view" that is semantically different) and introduces lazy().

Differential Revision: D923036
2013-08-19 10:15:17 -07:00
Jordan DeLong 0d56c48804 Always use lowercase names when tracking class aliases
I think the current situation is actually correct (we'll just
potentially have extra entries in the multimap), but this makes more
sense.

Differential Revision: D918976
2013-08-19 10:15:13 -07:00
Jordan DeLong 6a112e4866 Print duration of warmup requests
Differential Revision: D927403
2013-08-19 10:13:13 -07:00
mwilliams 26d097c39c Don't use low_malloc for preClass Funcs
They are rarely used at all, and never referenced from the
translation cache, so no need to put them in low memory.

Differential Revision: D930189
2013-08-19 10:13:13 -07:00
mwilliams ce47288fac Fix limit on low mem huge pages
The limit was still a bool, so we could only specify a limit
of 0 or 1. Since 1 was working fine, I've dropped the default from 200
to 32, and will test various values to see what works best.

Differential Revision: D929190
2013-08-19 10:13:12 -07:00
Mike Magruder 7f196d361e Add source location to async functions on the debugger async stack
Add source file and line to async functions on the debugger async stack. This information is only added for async functions which are not actually being executed. Those exist on the normal stack, and their location information is visible there. The location added for async functions which are not running is that of the yield which has caused the continuation to pause.

Differential Revision: D930103
2013-08-19 10:13:11 -07:00
Owen Yamauchi 7420c9a7ef Draw incision lines in translator-x64.h, delete some dead code
I deleted some dead code, but more importantly, organized the remaining
platform-specific declarations into thematic areas that I think can be
tackled (i.e. moved into explicitly platform-specific modules) as
self-contained units.

My determination of what's platform-specific was fairly loose. If it has
"emit" in the name it is for sure. Note that functionality that only
depends on the TCA type is *not* platform-specific: that was the point
of my diff to separate DataBlock and X64Assembler.

To be honest, I wasn't 100% rigorous on preserving access modifiers.
They're mostly the same, but some may have been changed in the shuffle.
I contend it doesn't matter that much since these members should be
moving to different modules soon, and also this class has so many
friends that most of its "private" members aren't really private as
such.

Because all the rearrangement makes the diff hard to read, here's the
list of declarations/definitions I found to be dead:

- emitDebugPrint, dumpStack, translatorAssert. Not used in the normal
  course of things, but it's possible people have been using them to
  debug; if so, I'll put them back.

- emitReRetransOpt (not dead, but since the definition was just a call
  to emitServiceReq and there's one callsite, I collapsed the chain)

- m_createdTime. It's declared in Translator (and only used there).

- emitIncRef*. These were moved to CodeGenerator earlier.

- toStringHelper. Unused.

- emitChainTo and emitIncCounter. No definition.

- {acquire,drop}WriteLease. We have a different abstraction for this.

- packServiceReqArg with one argument. It's not needed; that template is
  not recursive.

Differential Revision: D929657
2013-08-19 10:13:11 -07:00
Jordan DeLong aeac652f17 New StringData::append that uses reserve/escalate
Instead of having all the cases split out, this just goes
through the reserve/escalate paths.  I added geometric growth only to
the Smart mode in reserve (after the capacity check).  This makes it a
little easier to change how strings allocate (fewer allocation code
paths).

Differential Revision: D924293
2013-08-19 10:13:10 -07:00
Jordan DeLong 16a6ff7eeb Move increment_string() into StringData::inc()
After some changes I'm making locally, this will need to be
Mode::Malloc or Mode::Smart depending on the size of the new string,
which is easier to do from inside this same function. While at it,
let's make it reuse the buffer if it fits within the current
capacity().  (This allows small strings to stay small also; although
microbenchmarks on string increments are not particularly impressed by
it.)

Differential Revision: D920271
2013-08-19 10:13:02 -07:00
Jordan DeLong 83b4bf3acf Include the null terminator in string's capacity
I want to store the smart allocator size class here, so we
don't need to store it at the front of the smart malloced memory.  (We
can just tell smart_free how big it was, and possibly inline dropping
it on the appropriate free list.)  This isn't necessarily required for
that, but I decided to do it independently to make the changes easier
to think about.  (It's also maybe a marginal step toward not requiring
null terminators on the strings in general.)

Differential Revision: D917550
2013-08-19 09:01:33 -07:00
Bert Maher b789061519 Specialize SetNewElem when base is known to be array
Get rid of the switch-based dispatch on base type for
SetNewElem when we know that the base is an array.

Perflabs look like noise, except for one run that looks too awesome to
be believed:
https://our.intern.facebook.com/intern/perflab/experiment.php?diff_preview_id=2644370

Differential Revision: D927657
2013-08-19 09:01:33 -07:00
Aleksandar Ilic 0c3b36181b Hphp part for floats to thrift
Going together with D909976 and D913213.

Differential Revision: D921359
2013-08-19 09:01:32 -07:00
Sean Cannella d95ca0dc9a Add CodeGenHelpers[arch] for stateless helpers
Per discussion, create a stateless class for emitter utils that
can be implemented per-platform (to move code out of code-gen and
translator-x64)

Differential Revision: D927917
2013-08-15 15:19:36 -07:00
Bert Maher ecd61094e5 Add a stress-test mode that forces jitted execution
Sandcastle flib testing may be missing some coverage for the
JIT because tests that fail to get the write lease can execute in
interpreted mode.  Add a runtime option Eval.RequireWriteLease that
forces a thread to block on acquiring the write lease, so all test
code will be jitted.

Differential Revision: D921235
2013-08-15 15:19:35 -07:00
Jordan DeLong dc1f6c17eb static closures should inherit the late bound class
Mwilliams noticed an "obvious bug" in c_Closure::init, where
it always sets the late bound class to the context class in static
closures.  But it turns out thats what zend actually does.  This
behavior seems like a bug, so we're going to preserve the late bound
class.

Differential Revision: D814837
2013-08-15 15:19:35 -07:00
Edwin Smith 2f927eb29a Get rid of optional arguments in HphpArray helpers.
This just obscures what's going on and is making refactoring
more difficult.

Differential Revision: D927215
2013-08-15 15:19:34 -07:00
Owen Yamauchi 721a995726 Clean up punting to interpreter
There seems to be some strangeness left over from tx64 days. When the IR
took a slow exit trace, it would go through a "retranslate/interpret"
service request, which generated a stub translation that did nothing but
make an "interpret" service request.

I got rid of the BIND_JMP_INTERPRET and RETRANSLATE_INTERPRET service
requests, and replaced them with uses of the INTERPRET service request,
interping a single instruction.

Differential Revision: D927642
2013-08-15 15:19:34 -07:00
mwilliams b4d475fd9e Fix the build
I rebased past a rename of a private member
2013-08-15 15:19:33 -07:00
mwilliams 3072ea1e5b Don't let low_malloc hugify the entire tc
We carefully "enhugen()" portions of the tc. The problem is that low_malloc
maintains a high water mark, and every time it crosses into a new huge page
it marks everything up to the new high water mark huge. Since we allocate the
tc using sbrk, which allocates above the high water mark, the next time
low_malloc extends its arena, we mark the whole tc huge.

This adds some code to update the high watermark around the tc, and adds a runtime option to limit the number of huge pages used by low memory.

Differential Revision: D912684
2013-08-15 15:19:32 -07:00
Sean Cannella c1222d197a pull fixup outside of translator-x64
- pull fixup/sync code outside of translator-x64
- push codeblock related functions from asm-x64 down to codeblock to
  enable this

Differential Revision: D924632
2013-08-14 10:44:15 -07:00
Daniel Sloof 4a04f1ccba __get should be allowed for invalid properties
- Consistency with PHP, __get of an invalid property should
return an empty string instead of fatal

Closes #951

Differential Revision: D925220
2013-08-14 10:44:14 -07:00
Owen Yamauchi d6331ac3d9 Rename "no IR" stuff to reflect reality
This stuff all just punts to the interpreter, and there isn't such a
thing as a no-IR translation anymore, so let's clear this up.

I started thinking that maybe one of these steps isn't strictly
necessary. Currently, when we take a "slow" exit trace, we make a
RETRANSLATE_INTERPRET service request, which ends up creating a
"translation" that is nothing but an INTERPRET service request. This
feels like one more step than necessary; I think ideally we'd write out
an INTERPRET service request right in the exit-slow trace, but the
trouble right now is that at the point where we need to write it, we
don't know how many instructions should be interped.

Differential Revision: D925897
2013-08-14 10:44:14 -07:00
Mike Magruder 9b4501ce04 Add hhprof to news
The additon of hhprof, though under its own compilation flag, is worth mentioning

Differential Revision: D925547
2013-08-13 14:24:32 -07:00
Paul Bissonnette cfa4c3427c Adding OpAbs to codegen
fast absolute value computation and related optimizations

implemented Abs in interpreter

implemented Abs in codegen

added const folding for abs

updating docs

adding new test for abs()

Differential Revision: D896037
2013-08-13 14:24:32 -07:00
Eric Caruso 81f426be4b Translate CnsE and CnsU
These seem to be the last bytecode instructions left
to be translated that deal with namespaces and lookups, so we
might be able to get an OSS perf win out of them.

Differential Revision: D922132
2013-08-13 14:24:31 -07:00
Andrew Gallagher 4a9c32b507 hphp/util/service_data.cpp: add missing histogram #include
This file uses the ##getPercentileEstimate## templated function
without including the apprpriate header which defines it.  I'm
not entirely sure why building with gcc-4.8 triggers this issue
but it appears legit regardless.

Differential Revision: D923985
2013-08-13 14:24:31 -07:00
Andrew Gallagher b75d29d968 hphp: fix bug in JSON parser
gcc-4.8 exposed this issue via the end-of-array-subcript warnings.
The issue is that the top pointer is incremented before that check
to see if the push should happen.  If the push failed, the top
pinter is left incremented.

Differential Revision: D923932
2013-08-13 14:24:31 -07:00
Eric Caruso c58f9094eb Support for hhprof in client mode
A new runtime option will allow you to run in client
mode, but hang the execution thread until pprof collects the
heap dump or the HHProf thread timeout expires.

Differential Revision: D918754
2013-08-13 14:24:30 -07:00
Sean Cannella 8ec613f5b5 initialize thread locals before static constants
initialize thread locals first since static constant
initialzation assumes the memory manager is initialized

Differential Revision: D924209

Blame Revision: D915702
2013-08-13 14:24:30 -07:00
Andrew Gallagher 64654e47e0 hphp: remove unused local typedefs
gcc-4.8 complains about these.

Differential Revision: D923894
2013-08-13 14:24:29 -07:00
Drew Paroski 087e6e890c Remove more deprecated collections APIs
Differential Revision: D923014
2013-08-13 14:24:29 -07:00
Owen Yamauchi e1243c822d Fix build breakage
Post-rebase commit race.

Differential Revision: D924303
2013-08-13 14:24:28 -07:00
Drew Paroski da140be7e2 Miscellaneous cleanup
This diff gets rid of some mostly dead code and cuts down on the number
of uses of tvAsCVarRef().

Differential Revision: D923035
2013-08-13 14:24:28 -07:00
Paul Bissonnette 73553b7887 Remove native call Dbl -> Int conversion
use cvttsd2si to do conversion

Differential Revision: D905238
2013-08-13 14:24:27 -07:00
mwilliams 0ac0cf5564 Don't construct a new String/StringData for apc_unserialize
Every callsite of apc_unserialize constructed a String from a char*
and a length (involving at least one smart allocation, and a copy of the
data), passed it into apc_unserialize, which then extracted the char*
and length.

Just deal with the char*/length instead.

Differential Revision: D924015
2013-08-13 14:24:26 -07:00
Sara Golemon 35144c5398 Rewrite PHP function names to change _ to - in docComments
php.net manual URLs transform the function names
to use hyphens insteaf of underscores.  The autogenerated
docComments should reflect this.

Differential Revision: D922807
2013-08-13 14:24:26 -07:00
Joel Marcey ad3dcc4e7b Implement get_included_files()
PHPUnit self-test suite calls get_included_files(). Right now we return an empty array. That's not right. Implement correctly. Add and modify some tests as well.

Differential Revision: D922888
2013-08-13 14:24:25 -07:00
Owen Yamauchi de1b276ae7 Pull apart DataBlock and X64Assembler
This is one of the major spurious couplings I identified in my attempt
to get some code running in the ARM simulator. Currently, anything that
cares about the frontier of any of the code slabs is necessarily coupled to
X64Assembler, which doesn't make sense.

The solution in this diff is to remove DataBlock as a member of
X64Assembler. DataBlock is now in its own file, and TranslatorX64 has a
DataBlock member for each X64Assembler member. X64Assembler has a
pointer-to-DataBlock member. (I tried having it be a reference but that
doesn't work; in TranslatorX64::TranslatorX64() we have to construct
X64Assemblers without having their DataBlocks ready yet.)

I also discovered that the original reason for having DataBlock be a POD
type and having CodeBlock as a separate type seems to be gone, so I
consolidated the two classes and cleaned up some dead code.

There is more to be done here, which is to actually reap the benefits
and stop calling frontier() on X64Assemblers in translator-x64.cpp and
elsewhere. I'll do that in a separate diff because this state is a good
intermediate point.

Differential Revision: D918496
2013-08-13 14:24:25 -07:00
Mike Magruder 95e5b48cd9 Expose basic async stack in the debugger
Expose the async stack in the debugger. This is the stack of, say, generators driven from the ASIO extension. This is a modification to the where command. The new command type accounts for back compat between old servers/clients. I've added a shortcut, "wa", which is a bit faster to type.

I also modified the normal stack trace to not print bogus lines for functions with no file/line info.

Differential Revision: D920910
2013-08-13 14:24:24 -07:00
Jordan DeLong 8f8b12ae16 Some small changes for making valgrind clean when running hhvm with no args
We were reading uninitialized memory from tx64 member
variables and failing an assertion about the size of trampoline code.
(As far as I can tell, nothing really depends on the exact size of the
trampoline except for the guess about how many trampolines we can
fit.)

Differential Revision: D922916
2013-08-13 14:24:24 -07:00
Bert Maher 67aae18756 Test script support for debugging: write and compare printir logs
In trying to track down performance regressions I found it
was useful to generate printir:1 logs and compare them (Ed's idea).  I
figured others might find this useful so here's the test runner
support and script I used.

Differential Revision: D908406
2013-08-12 11:56:12 -07:00
Edwin Smith b62a3acde7 Rename files in runtime/server and facebook/runtime/server
Replace _ with -

Differential Revision: D922863
2013-08-12 11:56:05 -07:00
Drew Paroski eebf3bdced Make some collection APIs more lax about null and arrays
Looking at uses of the collection constructors, addAll, and setAll, I
noticed that it would be convenient if these methods tolerated null.
Also update Set::difference to support arrays.

Differential Revision: D923013
2013-08-12 11:33:04 -07:00
Jordan DeLong 8131f68221 Fix nemo errors for type aliases
:

Nemo is giving undefined class errors on type aliases.

Differential Revision: D918917
2013-08-12 11:33:04 -07:00
Drew Paroski 2a4f58d558 Fix HHVM to not allow collection literals in class constant definitions
HHVM was incorrectly allowing collections to be used in class constant
definitions. This diff fixes the bytecode emitter to throw a parse error
if a collection literal is used in a class constant definition.

Differential Revision: D922848
2013-08-12 11:33:03 -07:00
Sean Cannella 0084a8cc20 remove defunct segfault handler
- segfault handler never panned out and has been off for 1.5
years; cheaper to resurrect later from git than refactor to take it out
of tx64

Differential Revision: D922900
2013-08-12 11:33:03 -07:00
Sean Cannella bd7606c54f remove dead code from translator.h
remove dead functions/code from translator.h

Differential Revision: D922135
2013-08-12 11:33:02 -07:00
bsimmers 21a640569d Don't generate core files during test runs
When a diff that causes many tests to fail runs on contbuild,
it usually ends up timing out because the machine spends so much time
writing core files to disk. These files are almost never useful
anyway, so don't generate them.

Differential Revision: D922720
2013-08-12 11:33:02 -07:00
Benjamin Strahs 14245548e7 Fix missing openssl params
openssl_seal() and openssl_open() should both take an optional method parameter which allows you to select the symmetric cipher to use. This implementation is slightly different than Zend PHP, currently if you pass a cipher that requires an IV it segfaults in Zend, in this implementation it warns and returns false.

Differential Revision: D921384
2013-08-12 11:33:01 -07:00
Mirek Klimos ac56fafa55 Support for await on null expressions
The first implementation of async functions doesn't support
awaiting on expressions that are null. This adds support for this
in a way that the generator is not even suspended in these cases.

Differential Revision: D922499
2013-08-12 11:33:01 -07:00
Drew Paroski aed04c2799 Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5
The behavior of isset($x[$k]) and empty($x[$k]) where $x is a string has
changed in a recent version of PHP. This diff updates HHVM to match PHP
5.5's behavior. Note that HHVM still does not match Zend PHP 5.5 perfectly
in terms of warnings for these expressions; I've decided to put that off
into a separate diff.

This also brings HHVM up-to-date with respect to some edge cases for
automagically converting integer-like string keys to integer keys when
indexing into PHP arrays.

Differential Revision: D916630
2013-08-12 11:33:01 -07:00
Owen Yamauchi e42d796e26 Delete a bunch of dead code in TranslatorX64
I just went through the header and grepped for each member function
name, and it turns out a bunch of them were declared and not
implemented, or were implemented but not used.

This clarifies the picture of what assembler-coupled functionality
remains on TranslatorX64:

1. Func prologues and their transitive dependencies (including
unfortunate stuff like a duplicated implementation of emitIncRef).

2. One-time-use stub emitters.

3. Syncing VM registers.

This makes the project seems a little tamer. Func prologues are
definitely the biggest part of it.

Differential Revision: D921995
2013-08-12 11:33:00 -07:00
Mike Magruder e5f7c49775 Add a few more async tests for the debugger
Add a few more debugger async tests.

Differential Revision: D921498
2013-08-12 11:33:00 -07:00
Keith Adams cc70636040 Huge pages for server only, exclude targetcache by default.
Lots of scripts running in cli mode can quickly use up the huge page pool. Its better to not do that by default.

Even in server mode, it seems very suspicious to have large, thread-private segments of huge
pages. This should place heavy demands on the system's huge page resources,
and more worryingly, demand that scales up as threads go active.

Differential Revision: D885896
2013-08-12 11:32:59 -07:00
Daniel Sloof 9016abffaf use setCookie instead of manual header building
Instead of manually constructing a cookie, use the setCookie method
provided by Transport. This prevents the following kind of condition:

Imagine:

application runs setcookie with null params to delete a cookie.
application runs session_regenerate_id to get a new session id.
session_regenerate_id then constructs a new header through
m_responseHeaders.
Eventually, Transport will generate headers, but will always put
m_responseCookies after m_responseHeaders in the full header.

Uh oh! Now we have accidentally deleted a cookie due to incorrect header
order.

Closes #950

Differential Revision: D921467
2013-08-12 11:32:58 -07:00
Bert Maher b7034ab930 Allow guarding tracelets on ArrayKind
Enable guarding tracelets on ArrayKind when we can generate
better code for a specific kind.

Added specialized helpers for CGetM, FPassM, and IssetM of
vector-shaped arrays.  This eliminates an indirect call and allows the
entire array-access call stack to be inlined into the helper

Differential Revision: D873631
2013-08-12 11:32:58 -07:00
Mike Magruder 677b26fdf6 Remove a few extra vestiges of the debugger client api
Remove a few more bits left over from the client API, plus a little extra cleanup I noticed.

Differential Revision: D920393
2013-08-12 11:32:57 -07:00
Owen Yamauchi 876cbbb3eb Let $_SESSION be undefined until session start
In Zend, $_SESSION is undefined (i.e. reading it either directly or
through $GLOBALS results in an 'undefined' notice) until you call
session_start.

Right now we're not completely matching Zend on warnings, although we
get closer if you build with HHVM_MORE_WARNINGS (see
member-operations.h).

Differential Revision: D920224
2013-08-12 11:32:56 -07:00
mwilliams 67ec381c90 Fix incorrect UseUndeclaredVariable warnings
There were two bugs:

 - Methods from Systemlib traits that were imported into user
   code were still marked as system methods, so we didnt run
   type inference on them, so the parameter wasn't annotated correctly;
 - If we couldn't determine whether a function argument was by reference
   or not, we could end up marking *that* as being the thing that set
   the parameter. If later we figured out which function was being called,
   we marked it as *not* by reference, and then it looked like it was being
   used without being set.

With this diff, we set the system/user flag correctly when cloning methods,
and always mark the "declaration" of a parameter as the parameter itself.

Differential Revision: D920269
2013-08-09 10:30:43 -07:00
Sean Cannella fc59c6a00a Don't always call values() for array fcalls
We should only call values() when we absolutely have to (magic calls where the array is not a vector)

Differential Revision: D920504

Blame Revision: D917994
2013-08-09 10:30:43 -07:00
Sean Cannella 439d8d34fe folly::errnoStr is safer than Util::safe_strerror
- Eliminate Util::safe_strerror and use folly::errnoStr instead since the former is less safe as it doesn't preserve errno

Differential Revision: D920282
2013-08-09 10:30:42 -07:00
Sean Cannella 476bc58d6b don't hide errors from pthread_setspecific
pthread_setspecific can fail per the man page, we should be
checking the return value

Differential Revision: D919949
2013-08-09 10:30:42 -07:00
Jordan DeLong c98ebd8156 Fix a bug in StringData::escalate
Needed to delist and decref the shared variant.

Differential Revision: D920482
2013-08-09 10:30:41 -07:00
Sean Cannella 48babc3898 StringData allocator must be initialized
- For slow TLS ThreadLocalSingletons must be initialized

Differential Revision: D919977

Blame Revision: D907959
2013-08-09 10:30:41 -07:00
Jordan DeLong 6a500a5237 Fix static closures *not* to do LSB in the JIT
:

Apparently this is intentional bug compatibility with zend.

Differential Revision: D919411
2013-08-09 10:30:40 -07:00
Mike Magruder 29669189dd Enable ctrl-c during eval
Enable the support for signal polling during eval in the debugger.

Differential Revision: D910661
2013-08-09 10:30:40 -07:00
Mike Magruder d785895036 Add function to get dependency stack on WaitableWaitHandle
Add a function to get the wait handle dependency stack to the native implementation of WaitableWaitHandle. This will be used by debuggers and profilers to get the stack of dependencies for generators driven from ASIO.

Differential Revision: D919486
2013-08-09 10:30:39 -07:00
Vaishaal Shankar d5e6b2b96e unbroke type profiler
Fixed profiling implementation, moved soem of profiling ir opcode params into extra data

Differential Revision: D913367
2013-08-09 10:30:33 -07:00
Guilherme Ottoni 046c176b71 Avoid division by zero when aprof isn't allocated
That's it.

Differential Revision: D919880
2013-08-08 09:29:44 -07:00
Sara Golemon c03b010a7e Move MySQL config settings into ext_mysql
Organization and de-monolithification.

Differential Revision: D918185
2013-08-08 09:29:43 -07:00
Jordan DeLong 8eae97545a Smaller string mode tests, don't overlap mode with capacity
Looking at the generated code for various StringData mode
dispatch cases, there were 64-bit immediates being put in registers
often to test the format value.  We also did masks on the capacity
just to see that the string was small.  This switches to just load the
byte that actually contains the mode, and use a 32-bit integer for
capacity (the largest string size fits in this).  Small checks only
need to compare that byte with zero.

Differential Revision: D914034
2013-08-08 09:29:43 -07:00
Jordan DeLong 88d5a1d8b7 Fix a capacity under-estimate in StringData::escalate
This looks like it should be using cap.  (The allocation size
is cap + 1.)

Differential Revision: D917389
2013-08-08 09:29:42 -07:00
Jordan DeLong c1974eaf60 Fix a bug for typedefs to mixed when parameters are an object
Oversight in the case where it was an object.
(checkTypedefNonObj handled it properly.)

Differential Revision: D917712
2013-08-08 09:29:42 -07:00
Edwin Smith 59ac1d67e5 Rename files in hhvm
Differential Revision: D914023
2013-08-08 09:29:35 -07:00
Sean Cannella 0a3901d4cf Calculate dynamic invariant constants per process
- Cache and store invariant dynamic constants and set per
session instead of making more expensive calls

Differential Revision: D915702
2013-08-08 09:11:25 -07:00
Daniel Sloof 1ecc70eeff Fix arguments with __call and call_user_func_array
- Fix call_user_func_array to be Zend compliant, see new test
case

Closes #939

Differential Revision: D917994
2013-08-08 09:11:24 -07:00
Edwin Smith 860d410367 Streamline NewTuple and NewArray helpers
Rearrange the code so when we allocate an array from JIT code,
we call one helper where most of the code is inline.

Differential Revision: D917956
2013-08-08 09:11:24 -07:00
Scott Renfro 9a4fdfc892 Fix TLS CURLOPT when SSL_OP_NO_TLSv1_1 not defined
This was busted in two ways:
1. SSL_OP_NO_TLSv1_1 wasn't guarded by an ifdef in one location
2. SSL_OP_NO_TLSv1_1 was used instead of SSL_OP_NO_TLSv1_2
in one location.

Differential Revision: D917255
2013-08-07 09:55:23 -07:00
Jordan DeLong 258b71a5d5 Rename string_data-inl.h to string-data-inl.h
Differential Revision: D917064
2013-08-07 09:55:23 -07:00
Edwin Smith 783301a6f8 Rewrite findBody and findForInsertBody as functions taking lambdas.
The way we use these macros is exactly what lambdas are for, so
give it a try.

Differential Revision: D916121
2013-08-07 09:55:22 -07:00
Owen Yamauchi edfb74a80b Add a NativeCall pseudo-opcode to VIXL
We'll need the ability to call native functions (i.e. written in C++)
out of the simulated-ARM translation cache. VIXL already has support for
pseudo-opcodes that the simulator understands and treats specially (it's
a trap instruction with payload in some unallocated bits), so I added a
new one that will read a function address out of an inter-procedural
scratch register and arguments out of the usual argument registers, call
the native function, smash simulated caller-saved registers, and put the
return value in the simulated return value register.

Differential Revision: D916164
2013-08-07 09:55:21 -07:00
Edwin Smith de4259e8ae Rename rest of files in runtime/base
Differential Revision: D913884
2013-08-06 09:23:21 -07:00
Drew Paroski bf0846c516 Improve sort comparator warning message
Some developers were a little confused by the warning message printed when
a sort comparator returns a boolean. This updates the messages to be more
clear and more explicit.

Differential Revision: D909645
2013-08-06 09:23:19 -07:00
Aurelien Fredouelle 9e32fdc3fe Removed the Locale implementation
Symfony relies on class_exist('Locale') to check if the intl extension is
enabled. By removing this Locale class, we let Symfony use the stubs they
provide.

Differential Revision: D908679
2013-08-06 09:23:19 -07:00
Aurelien Fredouelle 663903371d Implemented highlight_file and highlight_string
Differential Revision: D913227
2013-08-06 09:23:18 -07:00
Paul Bissonnette 34524b59a1 Fixing issue in instructionsAreSinkable
the function wasn't actually checking if all the instructions were safe to sink

Differential Revision: D915210
2013-08-06 09:23:18 -07:00
Drew Paroski 4412f99b27 Remove unused runtime option "StrictCollections"
This runtime option was removed from all config files a while ago and is
no longer used. Let's get rid of it.

Differential Revision: D909886
2013-08-06 09:23:17 -07:00
Sara Golemon b0ea37ccfd Implement Redis session module
Translates session events into Redis commands

Differential Revision: D872896
2013-08-06 09:23:17 -07:00
mwilliams ca4f0e09ad Allow separate timeout for postsend
Add a new runtime option: Server.PspTimeoutSeconds.
If its zero, postsend gets the same timeout that the request was running under. If its less than zero, postsend will get min(time remaining for main thread, -Server.PspTimeoutSeconds), and if its greater than zero, it will get exactly Server.PspTimeoutSeconds.

In addition, fixed cli mode to respect Server.RequestTimeoutSeconds.

Differential Revision: D914478
2013-08-06 09:23:16 -07:00
Jordan DeLong 1abc7a911d Something already fixed these ones
Differential Revision: D910062
2013-08-06 09:23:16 -07:00
Jordan DeLong 398418ba56 Remove another TypedValue -> boolean helper
Differential Revision: D910135
2013-08-06 09:23:16 -07:00
Jordan DeLong b5c0ecb26f Fix a SEGV for zend's bug54265.phpt
Differential Revision: D910055
2013-08-06 09:23:15 -07:00
Jordan DeLong ae30d7480c Fix a few SEGVs relating to cyclic data with SETOP_BODY
Test cases inspired by zend test bug35239.phpt.  I think
there are other cases where SETOP_BODY should be SETOP_BODY_CELL, but
I looked at them mainly to see if they would crash, not if they were
optimal.  (Except I changed SetOpL which seemed to be doing tvToCell
twice for no reason.)

Differential Revision: D910025
2013-08-06 09:23:15 -07:00
Jordan DeLong 30e85006aa Fix SEGVs found by zend test bug35239.phpt
We dereferenced some potentially-freed memory only in order
to return something no one needed.  Remove the return value from
ObjectData::setProp.

Differential Revision: D909967
2013-08-06 09:23:15 -07:00
Sara Golemon e389ed81dd Implement a general purpose Systemlib SessionModule wrapper
To implement a session module in PHP, add a small C++ class
in runtime/ext/ext_session.cpp

  static class MySesionModule : public SystemlibSessionModule {
   public:
    MySessionModule() : SystemlibSessionModule('my', 'MySessionModuleImpl') {}
  } s_my_session_module;

Where 'my' is the name of the session handler (as known by the ini setting)
'MySessionModuleImpl' is the Systemlib PHP class implementing SessionHandlerInterface

Differential Revision: D872889
2013-08-06 09:23:14 -07:00
Vanilla Hsu 328607b4a8 use f_php_uname() to replace hardcoded PHP_OS
- PHP_OS should return the real OS instead of Linux

Closes #933

Differential Revision: D914263
2013-08-06 09:23:14 -07:00
Guilherme Ottoni 19c863bf42 Name next release
And also switch over to unambiguous date format.

Differential Revision: D914499
2013-08-06 09:23:14 -07:00
Chip Turner a0cdd8300e (retry) Fix bug in mysql_next_result's return value that confused "done" with "error"
The MySQL documention states that mysql_next_result's return
values are:

0	Successful and there are more results
-1	Successful and there are no more results
>0	An error occurred

However, we were casting it to a bool, meaning errors and "all done"
were mixed into the same result.

This diff brings back the full error range.

This diff requires D912547, which fixes unit tests to accept both the
new and old return value types.

Differential Revision: D912553
2013-08-06 09:23:13 -07:00
Jordan DeLong 0c2dc63438 Disable apparently broken dead store removal in hphpc
Hphp optimizes code like ($k += foo) into $k + $foo even if
$k is referenced again later in the function.

Differential Revision: D914064
2013-08-06 09:23:13 -07:00
Bert Maher b4fe8dc9fb Streamline a bit of code in AssignValHelper
The old code was constructing a Variant on the stack just to
decref it via the destructor.  Just call the decref directly and avoid
a few memory operations.

Differential Revision: D913228
2013-08-06 09:23:12 -07:00
Edwin Smith 251ebf9685 Rename files in runtime/base, part 7
Differential Revision: D913883
2013-08-05 14:42:18 -07:00
Edwin Smith 55494c2443 Rename files in runtime/base, part 6
Differential Revision: D913699
2013-08-05 14:42:17 -07:00
Edwin Smith 03fec81145 SetStr and AddStr methods on a Vector do the same thing.
Since vectors are guaranteed not to have strings, set and
add are identical.

Differential Revision: D914016
2013-08-05 14:42:17 -07:00
Edwin Smith 355a49c38f Rename files in runtim/base, part 5
Differential Revision: D913077
2013-08-05 14:42:17 -07:00
Stephen Chen e986ae1387 make the fb303 server work with port takeover
Make the fb303 server work with port takeover. We need to give it the same
treatment as admin server / satellite servers. Sorry I missed this part before
and being lame.

Differential Revision: D897344
2013-08-05 14:42:17 -07:00
Jordan DeLong c608b6cbd1 Some const-correctness fixes for collections
Gets rid of a TODO from when I implemented cellEqual.

Differential Revision: D911145
2013-08-05 14:42:16 -07:00
Jordan DeLong d9cb5f5d9a Make StringData constructor/destructor private
Everything has to go through StringData::Make or
StringData::MakeMalloced now.

Differential Revision: D909781
2013-08-05 14:42:16 -07:00
Jordan DeLong 871ba9aafd Optimize StringData::release a little
Strings are usually small, and failing that, usually smart
allocated.  Also, release() doesn't need to check for a null pointer
now that it's not controlled by the DELETE macro.  This just inlines
the small path and gets rid of the null check for now.

Differential Revision: D907960
2013-08-05 14:42:16 -07:00
Jordan DeLong 5cfd77fd49 Don't use NEW and DELETE macros for StringData
This is a step toward having StringData take control over how
it talks to the smart allocator based on its constructor parameters.
For now nothing is done to prevent allocation without going through
the new proxy function, but the nested allocator type is renamed to
prevent adding new uses of NEW or DELETE.

Differential Revision: D907959
2013-08-05 14:42:16 -07:00
Paul Tarjan f8359e6b7f kill HasDocComment
Why does this exist? Can't we just rely on the key being there? I've seen tons of functions with this flag and no comment...

Differential Revision: D909139
2013-08-05 14:42:16 -07:00
Mirek Klimos 88f2569735 Basic support for async functions using continuations.
Adding basic support for async functions using continuations, which should be semantically fully equivalent to yield wait_for() etc.

Differential Revision: D911571
2013-08-05 14:42:15 -07:00
Mirek Klimos 2add534031 Moving type inference of generator calls to FunctionCall expr.
Let's move the type inference for generators from function scope to
function call, so that the original infered type is kept in func scope
and can be used later (will be useful especially for async functions
lates).

Differential Revision: D913970
2013-08-05 14:42:15 -07:00
Mirek Klimos 8801eff71b Parsing member modifiers refactorization.
Currently, normal functions are not allowed to have modifiers and
closures can be marked only with 'static' keyword, which needs special
treatment in the parser. Let's change it so that it's parsed in the same
way as method modifiers. This will help us later when introducing 'async'
modifier for both functions and closures.

Differential Revision: D913903
2013-08-05 14:42:14 -07:00
Edwin Smith 45ac3b1d99 Add a dedicated VectorInit helper for vector-shaped arrays.
This replaces ArrayInit's vectorInit constructor.  When we
know we're making a vector-shaped array, there's no need to
internally use the general array api; ArrayInit provides the
api, internally we do what's fastest.

Differential Revision: D903252
2013-08-05 14:42:14 -07:00
Edwin Smith 838df51012 Refactor HphpArray internal helpers
Create and use set[Val,Ref] and init[Val,Ref,Lval,WithRef]
helpers, to factor out tricky, repetitive code.  These will
get even more airplay as we add more shapes.

This diff also fixes a bug in PopVec(): we need to erase the
value (and update the array's fields) completely before
calling decref on the value.  Getting this wrong can mess
things up with array<->object cycles because calling decref
can reenter another array method, which would see the fields
in an invalid state.

Differential Revision: D905136
2013-08-05 14:42:14 -07:00
Herman Venter 205ec4913f Use unit->isInterpretOnly() inside JIT, not VM, so that debugger eval can invoke JITted code
The units that result from Eval code injected by the debugger should always be interpreted because they are used once only, however, any code invoked by these units should be JITtable. This diff moves the test for disabling the JIT from VMExecutionContext to Translator::isSrcKeyInB. It also fixes a cut&paste error that inverted the logic for Unit::isInterpretOnly().

Differential Revision: D913723

Blame Revision: D904873
2013-08-05 14:42:14 -07:00
Joel Marcey 3807e939bd Fuller implementation of get_defined_constants() to support categorization
The PHPUnit test suite calls get_defined_constants(true), for categorization. We threw. Now we don't. Now we actually do something sort of correct, but not fully correct. We have a "user" and "core" constant categorization. Function cleanup and consolidation. That's good. But Zend categorizes even more into extensions. This is a first step. And two (2) tests now move from zend/bad to zend/good.

Differential Revision: D909942
2013-08-05 14:42:14 -07:00
Herman Venter e5983c0e98 Handle case where a break point is hit followed by a continue that returns to the break point without intermediate interpreted instructions.
Breakpoints correspond to source lines, not byte code operations, so more than one operation may correspond to a break point. Each operation checks for breakpoints, so breakpoints are disabled when encountered, otherwise commands such as continue and next would get stuck on a line until all the byte code operation for a line have been carried out. Such break points are re-enabled as soon as a byte code for another line is executed. This does not work if no other byte codes are carried out (i.e. if JITted code runs) until control loops back to the disabled break point. Consequently the disable logic now keeps track of the offset of the byte that first triggered disablement. If the break point is still disabled by the time control comes back to that byte code, the break point is temporarily enabled.

Differential Revision: D909092
2013-08-05 14:42:13 -07:00
Eric Caruso 050f5d56b7 Record block postconditions and use them to prune CFG arcs
The region selector will now refrain from choosing paths
through the translation CFG where the postconditions of the
sequence of blocks chosen up until that point have no chance of
passing guards.

Differential Revision: D907313
2013-08-05 14:42:13 -07:00
Mike Magruder e85a361d34 Remove the debugger client API
The debugger's API mode added a lot of extra complexity to the debugger client for minimal value. It also had a bunch of bugs, and unnecessarily tied alternate debugger clients to the command line client implementation. Deleting it.

Differential Revision: D912729
2013-08-05 14:42:13 -07:00
Scott Renfro 4dfcee9335 Add CURLOPTs to override TLS options from PHP
This will let us use TLSv1.2 or specialized cipher suites on internal
requests while avoiding breaking Microsoft and other partners on
external requests.

Differential Revision: D912541
2013-08-05 14:42:13 -07:00
Scott Renfro f0d652d9ba Add RuntimeOption::TLSClientCipherSpec
We need a way to configure which cipher suites are used when
we are acting as a TLS client using Curl. This option accepts
the standard OpenSSL cipher suite spec, which will allow us
to turn off some cipher suites.

Upgrading OpenSSL without this will cause us to send too many
cipher suites in the client hello, crashing Bing's F5 load
balancers.

Differential Revision: D911814
2013-08-05 14:42:13 -07:00
Edwin Smith 98fdfc266b Rename files in runtime/base, part 4
type_* and tv_*

Differential Revision: D912522
2013-08-05 14:42:13 -07:00
Owen Yamauchi c75bae5af3 Delete atomic_inc
This was a little weird: I deleted the definition first, and everything
compiled because all the usages now are behind ifdefs that we don't test
regularly. In the interest of not ruffling feathers over deleting this
code, I just went ahead and made the changes. I would like to suggest
deleting all this stuff, especially the GOOGLE_HEAP_PROFILER stuff, for
which the make target has been deleted for a long time.

Again, all the usage sites are using the default memory order specifier,
which is memory_order_seq_cst. They could stand to be relaxed, but I
didn't find it worthwhile.

I'd also like to replace atomic_acquire_load and atomic_release_store
with portable and correct alternatives. We really just shouldn't be
rolling our own atomic primitives.

Differential Revision: D909903
2013-08-05 14:42:13 -07:00
Owen Yamauchi aba544ba90 Fix some macro name collisions in vixl
As I try to include vixl from the jit backend, these macros are clashing
with ours. Codemod them all to use our macros from util/assertions.h.

Differential Revision: D912687
2013-08-05 14:42:12 -07:00
Mike Magruder 6cdbb86af5 Delete CmdUser
One more step on the road to deleting the hphpd client API.

Differential Revision: D908926
2013-08-05 14:42:12 -07:00
Edwin Smith 7e528ecb84 Coerce uninit->null in HphpArray 'add' functions.
The vector shape code calls addVal() in more ways than
before, so there might be client code seeing uninit when
they used to see null before.

Differential Revision: D912686

Blame Revision: D879416
2013-08-05 14:42:12 -07:00
Sara Golemon 3e85221156 Add literal and pattern exclude option to test/run
Run a whole suite except for specified tests

Differential Revision: D912868
2013-08-05 14:42:12 -07:00
Edwin Smith 4cb3db473e Rename files in runtime/base, part 3
renamed runtime/base/*file*

Differential Revision: D912500
2013-08-05 14:42:12 -07:00
Edwin Smith 0b6b336922 Rename _ to - in runtime/base, part 2
Differential Revision: D912410
2013-08-05 14:42:11 -07:00
Sara Golemon f27622b4e1 Merge pull request #932 from danslo/libevent
register_libevent_server has to be prefixed on OSX.
2013-08-05 10:22:17 -07:00
Daniel Sloof 3ebe6c3414 register_libevent_server has to be prefixed on OSX. 2013-08-02 23:52:46 +02:00
Mike Magruder ea77c958ba Fix segfault in CmdNext at request start
Request Start has no activation record on the stack, but Next is quite valid and should still work. Modified to tollerate the lack of act rec.

Differential Revision: D908499
2013-08-02 14:22:12 -07:00
Edwin Smith 53df4a7c53 Fix a few uninit_null() sites should be regular null.
I found the one in ArrayUtil::Map while debugging the array code,
and the others are just from inspection.

Differential Revision: D906683
2013-08-02 14:22:11 -07:00
Edwin Smith 4aba0c8a08 Rename runtime/base/zend_* to zend-
Incrementally renaming foo_bar.* to foo-bar.*.  runtime/vm
is nearly done, getting started on runtime/base.  This does
a dozen or so files, will do more in separate diffs.

Differential Revision: D910489
2013-08-02 14:22:10 -07:00
mwilliams 7eb3f8fb4e Revert "Fix bug in mysql_next_result's return value that confused "done" with "error""
Differential Revision: D911994
2013-08-02 14:22:05 -07:00
mwilliams 27bb515314 Revert "Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5"
Differential Revision: D911544
2013-08-02 14:22:00 -07:00
Guilherme Ottoni 613ac4e7d3 Only enable PGO for hot functions in server mode
This seems to get JitRegionSelector=hottrace working in perflab.  I
still left all functions being profiled in non-server mode, so that we
can run tests and measure benchmarks.

Differential Revision: D908942
2013-08-02 14:21:59 -07:00
mwilliams 0e5e165224 Unrevert "Raise a recoverable error when Obj->Str conversion fails""
Differential Revision: D906304
2013-08-02 14:21:52 -07:00
Paul Tarjan 8b78248845 fix recursive server rewriting
If a URL doesn't exist and is going to 404, we set `m_originalURL` to the 404 handler, but don't update the boolean to the fact that it hasn't been rewritten yet.

Differential Revision: D911365
2013-08-02 12:58:00 -07:00
Mike Magruder 5e6cb40a28 Fix debugger protocol break
I slipped and locked the wrong mutex on the signal polling thread with a recent diff, allowing two threads to send to the client at the same time. Fix that, and remove the other similar lock which was superflous.

Differential Revision: D911162

Blame Revision: D897309
2013-08-02 12:57:58 -07:00
Bert Maher 99685ccdd1 Fast path for intermediate Elem ops when the base is an array
We can call faster helpers for intermediate m-ops when we
know the base is an array, saving us a switch-table dispatch in
Elem().  In practice this only applies to the first intermediate m-op,
because subsequent ops won't have known type.  At least for now.

Differential Revision: D903464
2013-08-02 12:57:57 -07:00
Owen Yamauchi b2db98d0c6 Delete GOOGLE_HEAP_PROFILER and transitive dependencies
As far as I know we haven't used this in a while, we don't build with it
regularly, and in fact the Makefile with the commands to build with it
has been deleted since right around the fbcode transition.

It turned out to be the only thing holding LeakDetectable in the
codebase, as well as a runtime option.

We should just use jemalloc's profiling now if we need heap profiling,
and maybe a bit of valgrind too.

Differential Revision: D910760
2013-08-02 12:57:31 -07:00
Aurelien Fredouelle e4fc177c16 Cache the current SessionModule when calling set_save_handler
When the user provides a custom SessionHandler via the function
session_set_save_handler, we need to cache the current SessionModule,
as it will be the one called by the user's SessionHandler.
Also added a check to make sure we don't call set_save_handler when
the current handler is already a user-defined one.

Differential Revision: D910794
2013-08-02 12:55:38 -07:00
Vaishaal Shankar 76b6cdee6a Type profiling implementation
I've implemented type profiling in the jit, I added an ir opcode that will log one parameter or return value of a function. I emit that opcode during an FCall, and during a RetC. Each Func object maintains an array of atomic hashmaps (for each parameter), and the atomic hashmaps are basically just counters for each type at runtime.

Differential Revision: D890038
2013-08-02 11:10:32 -07:00
Herman Venter 52503f5ea8 Do not cache units containing eval code created by debugger
A number of debugger commands end up doing an eval inside the VM. These eval's are ad-hoc and are performed in human time scales. There is no need to cache them. Consequently, call compile_string directly, rather than call it via compileEvalString (which does caching). Also make sure that the result of compile_string is always interpreted so that no JIT caching happens.

In principle, caching ought not to matter, but another bug is causing the JIT to fail an assertion if a cached eval string is recompiled in a context where variables that were bound are no longer bound.

Differential Revision: D904873
2013-08-01 18:27:25 -07:00
Mike Magruder 125939e6e6 Make ctrl-c in hphpd just a little less annoying
Modify ctrl-c handling in the debugger to give up and kill the client after three presses, rather than 10 seconds. Change the wording as ctrl-c is pressed to hopefully be more clear.

Differential Revision: D908728
2013-08-01 18:27:24 -07:00
Owen Yamauchi 9a135bdf6f Delete atomic_dec
Resurrecting this thing I did ages ago. It's mostly similar and
mechanical, except for the stuff in SharedVariant. I got rid of the
anonymous union and struct because that doesn't play nice with the
std::atomic constructor. The static asserts below should give us all the
same guarantees we had before.

Note that I'm freely using operator++ and operator--, which use the
sequentially-consistent memory order for their underlying ops. However,
I've looked on both x64 and ARMv8, and these ops in particular do the
exact same thing regardless of what memory order specifier you pass.

Differential Revision: D909344
2013-08-01 16:07:33 -07:00
Sean Cannella 4beebed3b2 fix license script after zend folder flattening
- don't add zend license to all files in runtime/base
- exclude vixl from license path

Differential Revision: D910454
2013-08-01 13:31:51 -07:00
Herman Venter 5d012ac1f0 Log unexpected exceptions that occur when carrying out debugger commands
When we hit a breakpoint while processing a CmdEval, we print the line that we hit the breakpoint (which we see), then we send a nested CmdList to the proxy to get the source file. There is no handling of exceptions in CmdList::onServer(), so any exception would bubble out of the server-side command execution. Normally an exception at such a point would cause the proxy to shutdown, but there is a ton of quite general error handling around eval, and it looks like it will swallow the exception and merrily attempt to complete the processing of outstanding CmdEval, thus sending a CmdEval to the client and generating the output we see.

This diff adjusts the code in the catch(...) block in DebuggerProxy::processInterrupt() to log instead of trace, and introduce a similar catch of Exception to dump what we can about the exception. That would give us more data to start to track this very transient problem down.

Differential Revision: D908369
2013-08-01 13:29:41 -07:00
Drew Paroski b947636a57 Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5
The behavior of isset($x[$k]) and empty($x[$k]) where $x is a string has
changed in a recent version of PHP. This diff updates HHVM to match PHP
5.5's behavior. Note that HHVM still does not match Zend PHP 5.5 perfectly
in terms of warnings for these expressions; I've decided to put that off
into a separate diff.

This also brings HHVM up-to-date with respect to some edge cases for
automagically converting integer-like string keys to integer keys when
indexing into PHP arrays.

Closes #844

https://github.com/facebook/hiphop-php/issues/844

Differential Revision: D905081
2013-08-01 13:29:40 -07:00
Bert Maher 7fc005b6f4 Expose specialized class guards to IR
Guards on object class (and, eventually, array kind) need to
load the ObjectData to get at the class.  This is the same operation
as a LdLoc, so if we use that IR instruction to implement the class
guard we can CSE the LdLoc where the object is actually used.

Differential Revision: D906267
2013-08-01 13:29:40 -07:00
Jordan DeLong e51a04eaae Convert LdGblAddrDef to use native-calls
Differential Revision: D903863
2013-08-01 13:29:39 -07:00
Jordan DeLong d618384e11 Cut down some on cgCallHelper overloading
Factor destType and the destination register/ssa situation
into one parameter instead of a family of up to 3.  Remove the TCA
overload (casting to TCA at every callsite is no more convenient than
making a CppCall at every callsite).

Differential Revision: D903862
2013-08-01 13:29:39 -07:00
Jordan DeLong 3573e13e54 Directly call several conversion functions from the TC
Skip little wrapper functions for few non-virtual member
functions, and add support for immediates to native-calls so we can
call StringData::toInt64 directly with the defaulted argument.

Differential Revision: D903835
2013-08-01 13:29:39 -07:00
Jordan DeLong b8310bab3b Store CppCall objects instead of TCAs from native-calls.cpp
I did this because I thought we couldn't call member
functions the way things are, but apparently the direct interface
check stuff was already doing it, just with appropriate casting
through Util::getMethodPtr.  This still seems nice though, so I'm
putting it up (less casting in the actual table...).

Differential Revision: D903831
2013-08-01 13:29:34 -07:00
Jordan DeLong ab3118df75 Remove now-redundant convCellToBoolHelper
It's just cellToBool.

Differential Revision: D903823
2013-08-01 11:57:47 -07:00
Chip Turner f43ba24414 Fix bug in mysql_next_result's return value that confused "done" with "error"
The MySQL documention states that mysql_next_result's return
values are:

0	Successful and there are more results
-1	Successful and there are no more results
>0	An error occurred

However, we were casting it to a bool, meaning errors and "all done"
were mixed into the same result.

This diff brings back the full error range.

Differential Revision: D907075
2013-08-01 11:57:47 -07:00
bsimmers 34e7b6b7c1 Fix region translator tests
A few of the diffs I rebased onto each other and pushed last
night didn't play nice with each other.

Differential Revision: D908416
2013-08-01 11:57:46 -07:00
Jordan DeLong 5e3ae9637f (Re)move a few more unused/out-of-place functions on StringData
StringData::getPrecomputedHash was unused.  The
isValidVariableName thing was a thin wrapper on a zend function that
is hardly used, and it shouldn't be a member function anyway.  The
convert_double_helper and convert_integer_helper also shouldn't be
member functions, and the former duplicated buildStringData(double)
too much for me so I removed it.

Differential Revision: D903915
2013-08-01 11:13:19 -07:00
Jordan DeLong d50b200caa Remove buildStringData(litstr)
Barely used.

Differential Revision: D903895
2013-08-01 11:13:19 -07:00
Jordan DeLong 5662c99c30 Some String-related micro cleanups, comments and unneeded function removal
String::set was one of two users of StringData::Escalate.
Leaving the remaining use alone for now until I know where it'll go.
Reordered some members and updated some comments.

Differential Revision: D903882
2013-08-01 11:13:19 -07:00
Jordan DeLong 719a46546f StringData::m_count doesn't need to be protected
Also move private helpers ahead of private data.

Differential Revision: D903874
2013-08-01 11:13:18 -07:00
Jordan DeLong 3c29f15450 Remove comment referring to closed task
Differential Revision: D903869
2013-08-01 11:13:18 -07:00
Sara Golemon 132241f5e5 Implement session_status()
And export PHP_SESSION_(NONE|DISABLED|ACTIVE) constants.

Differential Revision: D908419
2013-07-31 12:25:21 -07:00
Guilherme Ottoni 2a91b4f540 Don't pass type prediction after Div interpOne
This is generating CheckTypes even when the value is not used.

Differential Revision: D907386
2013-07-31 12:25:21 -07:00
huzhiguang 3bbb2d22e7 fix compile_string memory leak
Fix memory leak in compile_string

Closes #879
Closes #917

Differential Revision: D908222
2013-07-31 12:25:20 -07:00
bsimmers e63215987c '_' -> '-' in runtime/vm/*
To be consistent with runtime/vm/jit

Differential Revision: D906425
2013-07-31 12:25:20 -07:00
Sean Cannella ba05c1d0d6 stats URL/response code filters did the opposite
- Per Github, URL/code filters, if specified, actually filtered
out only the code/URL as opposed to restricting it to the URL/code of
interest

Closes #912

Differential Revision: D906156
2013-07-31 12:25:19 -07:00
James Miller 64b1ffe624 gcc 4.8 compilation fixes
gcc 4.8 fixes from Github

Closes #889

Differential Revision: D900456
2013-07-31 08:06:33 -07:00
Eric Caruso 8f0d01d7bd Add runtime options for pprof server port and threads
As stated on the hhprof wiki page, this allows some
extra configuration.

Differential Revision: D899538
2013-07-31 08:06:32 -07:00
Eric Caruso a37f11eb4f Add cancellation endpoint to pprof server
You can now cancel profiling by sending a GET request to
/hhprof/stop. I also added an extra thread to the server so you
can un-hose yourself if one thread is waiting on a profile, but
it's still possible to deadlock if multiple clients try to get
the profile.

Differential Revision: D897271
2013-07-31 08:06:32 -07:00
Eric Caruso 584b8abf02 Add NextURL and Global profile request modes to pprof server
/hhprof/start will now also take parameters:
type = "next" (default) or "global"; "next" will profile the
next request or the next request to a particular URL if the url
parameter is present, and global will profile all requests until
stopped (but waits for at least one)
url = <some url>; if present and the request type is "next", then
it will get a profile for the next request to the given URL.

Differential Revision: D896989
2013-07-31 08:06:32 -07:00
Eric Caruso b0a8dde8de Add pprof server
hhvm will now respond to pprof requests. Start up a
server, curl /hhprof/start to put in a request to profile, then
fire pprof at /pprof/heap to get a heap profile.

Differential Revision: D896906
2013-07-31 08:06:32 -07:00
bsimmers d28cf653e9 interpOne bugfixes for vector instructions
This diff fixes a bunch of issues with interpOne of vector
instructions that only show up when the rest of the trace is
translated normally. I ran into them trying to perflab turning off the
vector translator.

Differential Revision: D901267
2013-07-31 08:06:31 -07:00
Drew Paroski 2ddb2189fd Set EnableXHP=0 by default, improve how the lexer works when EnableXHP=0
A couple of developers on github have reported that they've hit errors at
parse time with certain expressions that work under Zend PHP, or that they
have gotten output unexpected tokens from token_get_all(). A lot of this
is related to the lexer/grammar rules for XHP, so an easy solution to fix
a lot of these issues is to set EnableXHP=0 by default and to make some
changes to the lexer to make it more Zend PHP compatible when EnableXHP=0.

Closes #740
Closes #846

https://github.com/facebook/hiphop-php/issues/740
https://github.com/facebook/hiphop-php/issues/846

Differential Revision: D905986
2013-07-31 08:04:49 -07:00
Joel Marcey fdb61a462f Fix a small error in the IR for converting a resource to a string.
Something was just missed in an overall conversion effort. Found this in PHPUnit testing. @ptarjan was quick to diagnose!

Differential Revision: D907670
2013-07-31 08:04:46 -07:00
Mirek Klimos fb3f801604 Correction of D898769
I accidentally landed some old code with the previous diff
D898769. This will just remove it.

Differential Revision: D907355
2013-07-31 08:04:46 -07:00
Mirek Klimos 2b53df33bc Moving generation of generator bodies from compiler to bytecode emitter.
Generators are natively represented by 2 functions, which are now generated
by parser. Not only it's more natural to do this only when we emit bytecode,
but it will also allow us to reuse this logic for implementation of async
functions.

Differential Revision: D898769
2013-07-31 08:04:46 -07:00
Sean Cannella d0bf4ec6b6 remove option that doesn't work in OSS
- remove option from docs that doesn't work in OSS (becuase it
depends on a hacked version of mysql)

Differential Revision: D906111
2013-07-31 08:04:41 -07:00
Edwin Smith b92e3dedb0 Tighten checkRegisters()
Currently, check registers works by traversing down the dominator
tree.  Effects on registers from a dominator block can be seen
in each dominator child.  This will miss a rogue assignment that
happens in a block that does not dominate one of its successors.
For example if we mis-assign to a register in one arm of an if-
then-else block, we won't notice.

This diff changes checkRegisters() to propagate register state
along flow edges, so we can catch such rogue assignments.

Differential Revision: D903949
2013-07-31 08:04:41 -07:00
Sara Golemon 9e82e86d9e Fix handling of "not buildling from git" case
The fallback for repo-schema and compiler-id
generation when not building from git was to use the system
microtime.  Unfortunately, using a '.' in the repo-schema
leads to bad SQL table names.  Use an underscore instead.

Differential Revision: D906623
2013-07-30 12:43:34 -07:00
mwilliams 43a964cc13 Try to fix mysterious __sleep crash
We're seeing that some opt builds crash if you throw from
__sleep. After a lot of debugging, it looks like the eh_frame section
contains a bogus entry for php_sleep (in addition to the correct one),
and eh_frame_hdr's entry points to the wrong one (if I intervene in
gdb and point it to the right one, everything works).

I'm pretty sure this is a bug in gold (the eh_frame data appears
to be correct in object_data.o), and changes to unrelated code
make the bug appear and disappear.

I'm not sure exactly what the issue is, but php_sleep is basically a
hangover from hphpc days, so I'm killing it (and modifying the meaning
of HasSleep slightly - it now means what you expect). Not very satisfying
but hopefully it will work...

Differential Revision: D906292
2013-07-30 12:43:34 -07:00
Eric Caruso 21664d4b84 Add ProfileController, clean up ProfileDump and friends
This new static API will allow the coming pprof server
to request and fetch profiles, and VM threads to offer profiles
if they fulfill the currently active request. Some cleanup was
also performed to refrain from repeating stuff.

Differential Revision: D896872
2013-07-30 10:41:09 -07:00
Eric Caruso 9604aec155 Resolve SrcKeys to symbols so pprof can generate graphs
pprof will request symbols from a running HHVM via
POST request when you try to run it in remote mode. This adds
the ability to format SrcKeys in a reasonably human-readable
format so pprof can deal with them, and it can be manually used
by turning on TRACE=heap:3.

Differential Revision: D895234
2013-07-30 10:41:05 -07:00
Eric Caruso 83d4088bca Implement pprof-style heap profile formatting
Heap profiles can now be dumped in pprof format using
ProfileDump::toString. The memory profile instrumentation now
dumps this data at the end of every request when TRACE=heap:2
is set.

Differential Revision: D894112
2013-07-30 10:41:01 -07:00
bsimmers 3f1230f88f Add inlining support to the legacy region selector
When converting a Tracelet that contains an inlined FCall,
flag its block and then insert block(s) from the callee between the
FCall and the next instruction in the caller. The region translator
also required a few changes to support the inlined blocks.

Differential Revision: D863939
2013-07-30 10:40:56 -07:00
bsimmers a60daf4750 Turn JIT::Opcode into an enum class
Pretty straightforward. I renamed all the Op<name> opcodes to
just <name> to avoid collisions with the bytecode Op<name> constants.

Differential Revision: D867723
2013-07-30 10:40:52 -07:00
bsimmers 58e5f0caf0 Partially fix debugger pseudomain issue
I haven't completely figured out what's going on here, except
that we're running the same Func with and without the global varenv
attached. This was confusing the guard code and so we weren't emitting
guards for a local. This diff fixes up things so we do emit the
guards, but the global varenv issue still needs to be sorted out
before the new assert in translateTracelet can be left on.

Differential Revision: D899963
2013-07-30 10:40:48 -07:00
Eric Caruso b66e6c7a09 Compute square roots in the JIT
Pushes the sqrt builtin down to codegen for ints and
doubles, which might help on some microbenchmarks, and adds
sqrtsd to the assembler.

Differential Revision: D898146
2013-07-30 10:40:45 -07:00
Paul Tarjan 78157a5af5 don't call user-code in constructor
`rewind()` is an overridable method in children. composer does just that, and expects the objects to be fully formed by the time it is called. Lets use a private helper instead, so user-code isn't called in the constructor.

Differential Revision: D904037
2013-07-30 10:40:41 -07:00
Jordan DeLong fdfbbfc39b Memoize xed addressToSymbol callback
Apparently printir is so slow because of the symbol lookups
here.  Let's just leak a memoized table (we probably don't actually
have that many distinct symbols to look up).  Also, it looks like this
code writes one byte further than it's supposed to in the output
buffer (the docs for the xed callback say the buffer_length includes
the null terminator).

Differential Revision: D902605
2013-07-30 10:40:35 -07:00
Jordan DeLong 88b1cedd01 Fix a refcounting bug in Closure destructor
It didn't check if the reference count went to zero.

Differential Revision: D903740
2013-07-30 10:40:25 -07:00
Jordan DeLong 735c6c0cdc Closures with AttrStatic never have an object context
This check in the prologue didn't make sense to me---I'm
pretty sure it's impossible for the branch to be taken, since we've
already set up c_Closure::m_thisOrClass such that it will contain a
Cctx.  Am I missing something?

Differential Revision: D894574
2013-07-30 10:40:15 -07:00
Jordan DeLong 6443636f36 Some optimizations for closure creation
Inline some of the things into the TC so it can be
specialized on the closure type.  Also avoids spilling everything to
the stack to call init (which just pulls it back off and puts it into
the heap), and uses AllocObjFast instead of newInstance.  (We can't
quite get the super-fast-path version of AllocObjFast because closures
are extension objects and for now trying to convince it not to use the
m_InstanceCtor is a bit lame---we should probably just generate the
classes as php-level classes at some point so that'll just work.)

Differential Revision: D894569
2013-07-30 10:40:05 -07:00
Mirek Klimos 2c31ff8515 Letting doOptimize go into closure bodies.
As bodies of closures are not part of standard syntax tree, doOptimize
doesn't optimize them; this diff will fix this. It should have no
impact on performace as doOptimize is not used in WholeProgram mode.

Differential Revision: D904216
2013-07-30 10:40:00 -07:00
Sean Cannella b1762b9a07 fix OSX build issues
Differential Revision: D904206
2013-07-30 10:39:56 -07:00
bsimmers 98672dde4e Kill getKeyType[IS] and fix a emitVGetProp crash
getKeyTypeI/S/IS were artifacts of how keys were passed in
TranslatorX64 and no longer serve a useful purpose. emitVGetProp had
the same issue that was fixed in D902733 (no helper for Int keys).

Differential Revision: D904487
2013-07-30 10:39:50 -07:00
Owen Yamauchi 40104e57ea Remove remnants of parse-tester
Differential Revision: D904174
2013-07-30 10:39:34 -07:00
Paul Tarjan 8a87699411 remove typehints for FilesystemIterator
This class will happily take another `FilesystemIterator` as a param. Let the parent deal with throwing on bad params.

Differential Revision: D898524
2013-07-30 10:39:29 -07:00
Eric Caruso b057b96603 Support list unpacking in foreach keys and values
Zend 5.5 allows you to unpack arrays into the key and
value expressions in a foreach loop. This implements the same
functionality in HHVM.

Differential Revision: D900264
2013-07-30 10:39:25 -07:00
Sean Cannella a168863d5e remove dead option from docs
remove MaxStackDepth from docs, not used/implemented
remove unimplemented memcache-related statistics/settings

Closes #911

Differential Revision: D904848
2013-07-29 15:01:44 -07:00
Joel Marcey bb5dc1bbd2 Implement PHP_BINDIR (core constant)
Implement PHP_BINDIR PHP core predefined constant. PHPUnit (via PEAR) uses this constant in its self-test suite, causing many of them to fail on HHVM (possibly only because of the lack of this constant). Try to ninitially implement in such a way that it can be nimble enough for open-source, cross platform.

Differential Revision: D900077
2013-07-29 15:01:38 -07:00
Sara Golemon 834a1d331f Remove a bunch of separable extensions cruft
This code hasn't been relevant in a long time.

Differential Revision: D904562
2013-07-29 15:01:35 -07:00
Herman Venter 1b3c783dd4 Log status of all curl requests during test
Use exec("curl ...") instead of the curl API to make server requests, so that every interaction with the server can be traced and logged.

Differential Revision: D902614
2013-07-29 15:01:30 -07:00
Owen Yamauchi f4273f2c79 Normalize spelling of "prologue"
We had both "prologue" and "prolog" all over the place, and it was
starting to drive me nuts. I picked "prologue" because it seems to be
the more standard spelling. Both are valid in American English, but in
the rest of the English-speaking world, only "prologue" is standard.

Differential Revision: D904232
2013-07-29 15:01:25 -07:00
Daniel Sloof 9e36d6a2ae parallelize test runner on non-Linux platforms
parallelize test runner on non-Linux platforms

Closes #903

Differential Revision: D904203
2013-07-29 15:01:20 -07:00
Paul Tarjan 3ba3bccbc9 don't run phpunit test in repo mode
phars don't work in repos
2013-07-29 12:11:06 -07:00
Paul Tarjan 21780cb8e5 implement undocumented feature of RecursiveIteratorIterator
So this works in zend and composer relies on it, so I guess we should make it too...
2013-07-29 12:11:05 -07:00
Paul Tarjan 63bb1e6bf3 add phpunit test
I was having trouble gettig the binary into phabricator so the test wouldn't pass, so I committed the phar anyways. Now that the phar is in, a test should see it.
2013-07-29 12:11:05 -07:00
Paul Tarjan 063e9e75f7 don't return bad json
If there was an error during parsing, we shouldn't return anything.
2013-07-29 12:11:04 -07:00
Stephen Chen 57896cadfe Add priority to hphp's job queue
Add priority to hphp's job queue. Basically internally we keep multiple
queues. Whenever a worker gets notified of a job, it'll look at each queue in
order from highest pri to the lowest pri. This is inefficient if we have a large
number of priorities. But in reality we'll only have a handful of priorities. So
this should be faster than a heap implementation.

Add a runtime option to be able to specify a set of end points to be prioritized
over regular requests.

In practice, we'll only have 2 priorities, high and normal. For high, we only
plan to put status.php there. This is so the web server can respond to health
check even under high load.
2013-07-29 12:11:04 -07:00
Drew Paroski 707500591c Remove some deprecated collection APIs that are no longer used
There are a number of deprecated collection APIs that are no longer used
(all uses of them were removed over a week ago). Let's get rid of these.
2013-07-29 12:11:04 -07:00
Edwin Smith 59411c4a48 Add support for capturing stack samples, then counting them later.
StackTraceProfiler.count() captures a stack trace at the point you call
it.  It's also useful to create a stacktrace, then add it to a profiler
later on.  For example, create a stacktrace when you allocate an array,
then count it when the array reaches some state (destruction, growing,
changing shape, etc).
2013-07-29 12:11:03 -07:00
Edwin Smith bc03e4fad4 Use StaticStrings in getDataTypeString()
Doing some profiling of litstr creation, I noticed f_gettype() being
called a lot, but not using static strings.
2013-07-29 12:11:03 -07:00
Drew Paroski 53a869d1d6 Fix how "$obj -> class" is lexed
At present, "$obj -> class" (with spaces) causes a parse error under HHVM
but it parses okay on Zend. The problem is that HHVM's lexer treats "class"
as a keyword when there are spaces after the "->". This diff fixes HHVM's
lexer appropriately.

Closes #833

This fixes https://github.com/facebook/hiphop-php/issues/833 .
2013-07-29 12:11:02 -07:00
Jordan DeLong 7587932213 Remove hphp/util/parser/test
I added this in hopes it would make it easier to do parser
development faster---in practice I find myself preferring to just wait
on the build times for compiler/parser instead.  Changes to the parser
too often involve the need to fix the crazy callback interface over
there, and it's not worthwhile to maintain it in two places.  Oh well.

Making the parser more modular to develop on is probably worthwhile
but I'm calling this a failed attempt.

In case it scares anyone that I'm deleting tests: this test suite
wasn't really intended to find bugs, but I think it's unlikely it
would (the normal tests have to parse everything anyway).
2013-07-29 12:10:12 -07:00
Jordan DeLong 337160161d Fix an issue with CGetM on objects with an integer property keys
The implementation was trying to look up a specialization for
ints, but there isn't one, so it would hit an assertion on opFunc in
debug and call to a null address in release.
2013-07-29 12:10:12 -07:00
Jordan DeLong 8f2476ff5e Fix segv when class_alias is called with zero args
m_params is a null pointer when there's no arguments.
2013-07-29 12:10:12 -07:00
Edwin Smith 89c362e341 Clean up StaticString declarations
We've used a couple different styles, this consolidates on a single
style and moves a few declarations out of function bodies to global
scope.
2013-07-29 12:10:11 -07:00
Paul Tarjan cb4662c436 fix asCResRef
I wrote this before the resource diff landed.
2013-07-29 12:10:11 -07:00
Paul Tarjan b1f633f91d implement stream_is_local
needed for composer installation
2013-07-29 12:10:07 -07:00
Drew Paroski d3c421cb79 Separate resources from objects, part 2
In HHVM we've been piggybacking resources on the KindOfObject machinery.
At the language level, resource is considered to be a different type than
object, and there are a number of differences in behavior between objects
and resources (ex. resources don't allow for dynamic properties, resources
don't work with the clone operator, the "(object)" cast behaves differently
for resources vs. objects, etc).

Piggybacking resources on the KindOfObject machinery has some downsides.
Code that deals with KindOfObject values often needs to check if the value
is a resource and go down a different code path. This makes things harder
to maintain and harder to keep parity with Zend. Also, these extra branches
hurt performance a little, and they make it harder for the JIT to do a good
job in some cases when its generating machine code that operates on objects.

This diff introduces a new DataType called "KindOfResource", it separates
ResourceData from ObjectData's inheritance hierarchy, introduces a new
smart pointer types called "Resource" and "SmartResource", updates the
runtime as appropriate, and kills some more dead code in ObjectData and
ResourceData. I've tried to keep behavior the same for the most part and
resisted the urge to fix existing bugs with resources.
2013-07-29 11:25:56 -07:00
Guilherme Ottoni a1f16ea646 Kill comment about completed task
I forgot to take this out with D900055.
2013-07-29 11:25:00 -07:00
Guilherme Ottoni c0016ae59b Dump aprof code into separate file and teach tc-print about it
This avoids dumping a tc_dump_a file of more than 512MB.
2013-07-29 11:25:00 -07:00
Sara Golemon 8d9ae2c179 Remove retired options from CMake/Options.cmake
ENABLE_LATE_STATIC_BINDING
INFINITE_LOOP_DETECTION
REQUEST_TIMEOUT_DETECTION
HOTPROFILER_NO_BUILTIN
INFINITE_RECURSION_DETECTION
WANT_FB_LIBMCC
2013-07-29 11:23:45 -07:00
Jordan DeLong 0fa12ac543 Move JSON_parser stuff out of global namespace 2013-07-26 11:31:19 -07:00
Jordan DeLong b38e53d0e7 Add "static" to most InitFiniNodes
Some of them were neither static nor in an unnamed namespace.
2013-07-26 11:31:19 -07:00
Jordan DeLong dd9ecf559e Don't use malloc from pcntl_signal_handler
Not kosher.
2013-07-26 11:31:19 -07:00
Sara Golemon 095e163a1d Use m_conn rather than PDOStatement::dbh within PDOMySqlStatement
It's possible for PDOMySqlStatement to try to access
dbh before it's initialized, but m_conn will be set by the ctor.

Closes #851
2013-07-26 11:31:19 -07:00
Martin Matuska 778abf7ab1 ifdef Linux-specific GNU extensions/impls as such
- mark Linux-specific extensions as such
2013-07-26 11:31:18 -07:00
apuckey e70567994c fix shutdown crash when using PDO
- fix shutdown crash when using PDO

Closes #710
2013-07-26 11:31:18 -07:00
mwilliams b2bf67f7e5 Fix pagelet timeouts
Push the remaining time through to the pagelet's HttpRequestHandler,
and fix HttpRequestHandler::handleRequest to use the timeout we pass in
(the latter was an inadvertent omission from my previous timeout diff).
2013-07-26 11:31:18 -07:00
mwilliams cd5e74ec7e Fix type inference for ZendParamMode
Parameters of ZendParamMode functions aren't converted to the
destination type, so don't try to apply a type.
2013-07-26 11:31:18 -07:00
Bert Maher 88640588e3 Move NormalizedInstruction out of translator.h
In the name of making incremental builds faster when headers
change, I've pulled NormalizedInstruction out of translator.h and
replaced it with a forward decl.
2013-07-26 11:31:17 -07:00
Mike Magruder fb9f1405ce Remove ctrl-c test from debugger server test
We can never make the ctrl-c portion of the debugger server test 100% reliable. Removing that portion of the test. I'll replace it with something else soon. See task 2656173.
2013-07-26 11:31:17 -07:00
bsimmers ecf6c0a726 More cur*() -> live*() renaming 2013-07-26 11:31:17 -07:00
bsimmers 48dc5639f1 Rename curFunc() to liveFunc() 2013-07-26 11:31:17 -07:00
bsimmers c16d3b3536 Rename curUnit() to liveUnit()
curUnit and friends are evil and have been the source of many bugs
I've had to track down in the region translator. Time to force an audit of all
callsites. Most of the uses of curUnit() could be changed to grab the unit from
somewhere else, and the few where that wasn't reasonable use liveUnit to make
the intent more clear.
2013-07-26 11:31:16 -07:00
Bert Maher a1e6cb1ca1 Reduce boilerplate in RuntimeType constructors
RuntimeType has a lot of constructors that could share some
code, so I factored the common stuff into a private init() method.
2013-07-26 11:31:16 -07:00
Mike Magruder 05871951f0 Debugger: cleanup server-side when the client disconnects while in run mode
Server-side cleanup was all driven by having a request thread see that either the connection with the client is closed, or the stopped flag on the proxy is set. However, if a debugger's in the run state and there's just no incoming requests against the right sandbox, then that would never happen. However, the signal polling thread is perfect to notice, there were just issues coordinating the cleanup of the proxy.

Modified stop() on the proxy to be callable from any thread, and to initiate cleanup of the proxy but pass the final cleanup off to another thread which can complete it. The signal polling and dummy sandbox threads are owned by the proxy, so they can't complete the work themselves. There was logic to queue cleanup just for the dummy sandbox, so I turned that into proxy cleanup and have it cleanup both.

I'll investigate making a unit test using the new framework that will test this, but that will come in a later diff since this diff is already quite involved.
2013-07-26 11:31:16 -07:00
Ben Maurer a9e05eabf4 Shutdown listen socket during segfault
During a segfault, we continue to accept incoming connections. This is
bad as the web server is unlikely to do a good job of serving these well.
Here we close the listen socket as soon as we discover the server is crashing.

A more robust way to do this might have been to have an array of FDs that
are listening for incoming connections. We could have then closed those
from the signal handling thread. This would complete the operation more
quickly and also handle a case where the libevent thread wasn't running.
However, this version was quicker to write.

I didn't understand why some signals didn't trigger the Segfaulting variable.
Does anybody have insight into that?
2013-07-26 11:31:15 -07:00
Stephen Chen a112d17438 Add an option to hhvm to 503 requests if they have been sitting on the select queue for too long.
Add an option to hhvm to 503 requests if they have been sitting on the select
queue for too long. Threshold is configurable via runtime option and default off
for now. This works with either LIFO or FIFO mode. Basicallly before worker
dequeues a request, it peek at the beginning of queue to see if it's expired. If
so, it takes that off the queue and aborts the request without executing
anything.
2013-07-26 11:31:15 -07:00
Herman Venter b7ed094ed2 Use the same output formatting for = command as is used for the print command.
The = command uses formatting that is user customizable and subtly different, by default, from the formatting used by the print command and the variable command. This has historical roots. It seems that the debugger used to use print_r, which is brittle, and the customization hook was introduced to work around this brittleness. This work around is no longer necessary since the debugger now has its own, robust way of formatting values as strings. Also, the difference between = and print is a perennial source of confusion for debugger users.
2013-07-26 11:31:15 -07:00
Herman Venter 5d494456bc Display more diagnostic information in the case of test failure
When there is a failure in the test of debugging a server, give more diagnostics about failures to connect to the server.
2013-07-26 11:31:15 -07:00
Mike Magruder 0cc77bde72 Adjust error handling around socket closure for debugger
I had previously made the error handling in DebuggerCommand::Receive() too strict, and we'd fail to read available data from the socket when it was closed right after the data was sent. Loosened it, so if there appears to be data present we'll let the thrift layer have a chance to read the data.

I also moved the remaining log messages in that function to traces. There are cases where it is nice to see such a log message printed, but those are very rare and have not happened in the wild in the past many months. Log messages here particularly from the signal polling thread make our test output non-deterministic, and there's higher value in having stable tests :)
2013-07-26 11:31:14 -07:00
Drew Paroski 64b284d281 Fix silly bug when computing AttrDeepInit for a property
This diff fixes a crashing bug that can happen when multiple properties are
declared in a single statement and some of the properties are initialized
using collection literals, for example:

  public $x = Set {}, $y = 1;
2013-07-26 11:31:14 -07:00
Paul Bissonnette d63459b8e5 Adding floor and ceil to interpreter/jit
Added floor and ceil to the interp and jit, also fixed some type conversion simplifications.
2013-07-26 11:31:14 -07:00
Edwin Smith 5b42995fbd Fix leak in HphpArray::PopVec
If you pop the last element of a vector-shaped array,
we didn't decref the value or update the iterators properly.
2013-07-26 11:31:13 -07:00
Vanilla Hsu 2592a77248 fix embedded_data on freebsd
- remove hardcoded path in embedded_data
2013-07-26 11:31:13 -07:00
Chip Turner c051b9c3c2 Fix return types from AsyncMysql queries (allow NULLS, support variants)
We did not properly export NULL values as null; instead they
appeared as empty strings.  In addition, we returned all ints, floats,
etc, as strings rather than properly typed.

This diff adds support for typed return values (ie, ints, floats, etc)
rather than just strings.  It also changes returned maps and vectors to
have actual null values when the underlying result set returned nulls.
2013-07-26 11:31:13 -07:00
Joel Marcey a7c6c411e2 Support zend_version()
PEAR uses zend_version(). Let's support it too.
2013-07-25 14:00:11 -07:00
Sean Cannella a43fbbce08 disable failing test
This worked when imported
Due to a diff that was reverted
Because it broke other things
2013-07-25 13:59:56 -07:00
Paul Tarjan 647e3a7148 fix zend error message
I stupidly changed this without retesting. The message shouldn't have a newline in it.
2013-07-25 13:59:56 -07:00
Herman Venter fe3ca642be Remove obsolete debugger test suite
The debugger tests that are run via hphp/test/ext/test have now been replaced by tests that run via hphp/test/run, so they can be deleted as they test nothing additional and appear to be flaky.
2013-07-25 13:59:56 -07:00
Sean Cannella d618b30ed7 no POSIX timers on OSX
- unbreak OSX build

Closes #891
2013-07-25 13:59:55 -07:00
Sean Cannella 4eb23b6687 Revert "simplexml fixes for text children and casting" 2013-07-25 13:59:52 -07:00
Kyle Delong 70e0cf3568 HPHP/XHP: always pass file/line into XHP constructors 2013-07-25 13:59:40 -07:00
Paul Tarjan ad394c4f06 import phar tests
Now that phars sort of work, we can import their tests and they don't spew everywhere.
2013-07-25 12:10:59 -07:00
Paul Tarjan ed852dee7a implement read support for phars
A first pass at phar. The parsing logic was done from the spec:
http://www.php.net/manual/en/phar.fileformat.phar.php
2013-07-25 12:10:58 -07:00
Guilherme Ottoni 2f7088b1b3 Add an aprof code region and use it for profile translations in JitPGO mode
This diff generalizes the AHotSelector (now called AsmSelector) to
select an assembler among 'a', 'ahot', and 'aprof'.  'aprof' is only
allocated and used in JitPGO mode, and it's used for TransProfile
translations.
2013-07-25 12:10:58 -07:00
Paul Tarjan 8bec0a9f9c use correct class for RecursiveDirectoryIterator
That was one hell of a bug. They overwrote a subclass and expected the overwriting to stay when it created a new copy.
2013-07-25 12:10:57 -07:00
Paul Tarjan 6faa4e2ca6 handle file:// includes
Now that we can include urls, we shoudl handle `file://`.
2013-07-25 12:10:57 -07:00
Sara Golemon 9627f855ce Move RuntimeOption settings for APC section to ext_apc
Avoid the massive monolithic structure that it
runtime_options.cpp

Rename settings along the way to drop superflous "Apc" naming.
2013-07-25 12:10:57 -07:00
Eric Caruso 8ac589b4b7 Leak Units when memory profiling to prevent cleanup of Funcs and Classes
Memory profiling is going to rely on these things not getting
destroyed, so we are intentionally going to leak them in this case.
The use case of this is that the memory profiler is going to store
a stack trace as a bunch of SrcKeys, which can be used with D892173
to look up the original Func the stack trace goes through. Since we are
looking up the Func potentially much later than the SrcKey was
originally recorded, there is no guarantee that the Func will still be
around, or that we won't grab a pointer to it only to find that it is
in the middle of destructing and is thus full of garbage.
2013-07-25 12:10:56 -07:00
Eric Caruso 2a793e36dc Instrument smart allocator
Dumps information about allocation events in smart
allocator, and aggregates some information such as bytes
allocated per callsite in the current request (or across
requests). This information can be gathered in the heaptrace
command, and the information collected during the trace is
enough to find how much memory an object is responsible for
(i.e. keeping reachable).

It's all conditionally compiled because perflab showed a pretty
significant instruction regression if it was a runtime option.
You'll need to fbconfig with --extra-cxxflags=-DMEMORY_PROFILING
in order to use it.

This isn't done, but I wanted to get some feedback on where I
should take this (general design, what to log, where to dump
stuff, etc)
2013-07-25 12:10:56 -07:00
Eric Caruso a06d5fcbdf Add structs for holding heap profile dumps
These structs will eventually hold the heap profiling data
for PHP request heaps, so that it can be gathered and displayed
using the pprof tool.

This was tested by layering the smart allocator stuff on top and
making sure everything worked as planned. Nothing uses the structs
in this diff, so it's kind of difficult to test otherwise.
2013-07-25 12:10:55 -07:00
bsimmers d09abeb26d Support parameter reffiness in the tracelet region selector
This brings the tracelet region selector to 100% coverage,
though perf is still not at parity. Guard relaxation/specialization
and inlining are the big remaining features that will help perf.
2013-07-25 12:10:55 -07:00
bsimmers 631438f0fb Apply metadata to the ir in translateTracelet
In one of my pending region compiler diffs, I added code to forget the
values/types of locals after some FCalls (not doing so was wrong but we were
mostly getting away with it). This exposed an issue where the known type of a
local in the IR was less specific that what Translator::analyze was using. The
more specific type came from metadata on instructions after the FCall, so this
diff applies metadat to the IR before translating each instruction, using the
same code I wrote for the region compiler.

The changes to apply the metadata are pretty small; most of the
changes in this diffs are real bugs I found while attempting an
alternate solution.
2013-07-25 12:10:49 -07:00
Chip Turner 6bc3bf2d82 Change interface to ext_mysql C++ code to allow transporting underlying conns
This allows for connections to be created from existing mysql
connections as well as extracting the underlying connection from it.
2013-07-25 10:56:08 -07:00
Owen Yamauchi d0fdcfaef6 Fix warnings for various things being passed by reference
We were fataling when passing a list assignment expression with an
array-element RHS (like "$arr[0]") as an argument that the callee
expected to take by reference. Zend allows this, but with a warning. I
figured out the rules as best I can (this is one of those corners of
Zend where layers of insanity have piled up over time). I won't swear
that I got it 100% right w.r.t. whether we warn or not, but I'm pretty
sure we're closer to 100% right w.r.t. whether we fatal or not.
2013-07-25 10:56:08 -07:00
Owen Yamauchi 6451f9fc04 Delete GlobalCache, take 3
Pulling the trigger; it's unused post-tx64. This diff preserves the
ability to mark units as merge-only when the pseudomain only contains
assignments to known globals. When the unit is being merged, the set
operation goes directly to the global varenv instead of through the
targetcache (GlobalCache stored pointers into the global varenv's
NameValueTable).
2013-07-25 10:56:08 -07:00
Paul Tarjan 1c50cde17c fix subPath for RecursiveDirectoryIterator
Another RecursiveDirectoryIterator bug :( This time, subPath was totally wrong. It should only be adding on a little bit each time, not the whole path.
2013-07-24 10:35:47 -07:00
Paul Tarjan c1af7f57f5 fix str_split
This was coming up when installing Symphony using composer, and while I was in there I fixed a zend mode bug. We weren't doing the warning in the interpreter (and we were doing null instead of uninit). That was enough to move most of the tests over. The other problem is tasked.
2013-07-24 10:35:47 -07:00
mwilliams fe42263267 Fix lock rank violation assersions
There's a race in the emitter, where if we emit a unit (because,
it wasn't in the repo) fail to commit it, and then find the unit in the repo,
we destroy the unit we just emitted, and read the one from the repo instead.

This typically happens at RankFileRepo. A new change to Func::~Func makes
it grab the write lease in DEBUG builds, which is a lock rank violation.

Newly created Funcs never need the write lease, however, so aquire it
lazily.

This was happening running slow tests, because some tests are run multiple
times (potentially in parallel) with different runtime options (in fact, the
test code is duplicated in separate files).
2013-07-24 10:35:47 -07:00
Owen Yamauchi 5978586214 Import VIXL, an ARMv8 assembler/disassembler/simulator
This diff is intended primarily as a medium for everyone to look at and
discuss the code I'm planning to use as our ARMv8 in-memory assembler
and simulator. This is what I was about to spend weeks and weeks writing
myself, but thankfully ARM has done all that for us!

To get an idea of what it looks like to use VIXL, look at
test-assembler-a64.cc, at lines that begin with "__". Superficially, it
looks very similar to clients of X64Assembler. Things like x0, w1, etc.
are registers. "Operand" is a struct that encapsulates some of the extra
stuff tacked on to ARMv8 instructions -- e.g. when comparing against an
immediate, you can include a left-shift amount for the immediate, and it
will look like "Operand(x1, LSL, 1)" or similar.

The simulator is similarly easy to use. You set initial register values,
give it an instruction pointer, and say go. It runs until it hits a ret
instruction that takes it out of the top level, and then you can read
register values out of it. It can access memory just like native code
can.

VIXL includes its own abstraction for registers, and it's structurally
quite similar to our PhysReg. (It's defined in assembler-a64.h.) One of
the most nontrivial parts of this effort will be to figure out how to
unify these two abstractions.

The instruction coverage is internally consistent (i.e. the simulator
and disassembler can deal with any instruction the assembler can output)
and is almost certainly enough for our needs. Even if it's not, the code
is pretty clean, and it won't be hard to add whatever we need.

The big thing I'm not yet sure about is the implementation of nonlocal
jumps. The usage examples that come with VIXL (but I'm not including
here; see the original github) use jumps, but only within the small
snippets they emit. There's nothing that resembles our jumps between a
and astubs. This might be something we have to hack in, but it shouldn't
be too hard. The one potentially tricky part will be to support jump
smashing. If we have to encode a jump as multiple instructions, we won't
be able to smash it atomically. The only viable alternative I can think
of is to have a "jump target table" on the side, emit an indirect jump
in code, and smash the table entries instead of the code.

The open-source distribution of VIXL is built with scons, but it was
near-trivial to get it building with our internal system. To build the
library, I just had to change the include paths. To build the tests, I
deleted the custom test driver that came with VIXL and converted the
test files themselves to use gtest. This was mostly a matter of tweaking
the macros to use gtest asserts.

I also fixed lint errors (NULL -> nullptr, include ordering, static at
namespace scope, ...)

About licensing. The code is under a 3-clause BSD license, and the
license header is preserved in all the files I pulled in.

Pulled from https://github.com/armvixl/vixl at ad96eda894.
2013-07-24 10:35:46 -07:00
Sara Golemon 1824c359ea Pass entire Hdf to Extension::moduleLoad()
This lets us move parsing of runtime options
to the extensions which actually use them.

Nobody is currently using this functionality, so changing
what gets passed isn't a BC break worth worrying about.

I'll post some followup diffs pulling things out of
RuntimeOptions.
2013-07-24 10:35:46 -07:00
Paul Tarjan b1d102c698 import all 5.5 tests
and spruce up the import script while I'm in there. Lots of new tests 'passed' because of the skipif

We are now at 45.4% pass rate
2013-07-24 10:35:45 -07:00
Guilherme Ottoni d078c2b895 Add initial framework for PGO in the JIT, and use it for trace-region selection
This diff adds an initial framework for profile-guided optimizations
in the JIT.  Two new translation modes are added, effectively creating
a multi-gear JIT:

  1. Profile: this collects profiling data, which includes execution
              counters and type information.
  2. Optimize: this uses data collected by Profiling translations to
               produce optimized translations.

Right now, the Optimize gear is solely used to produce larger
compilation regions (traces), which increase the scope of
optimizations exposed to the JIT (compared to tracelets).  This is
still work in progress, and it's disabled by default.

This diff also fixes a number of bugs exposed by trace regions, gets
tools/reduce working again, and makes a number of improvements to
tc-print related to the new translation modes.
2013-07-24 10:35:45 -07:00
aravind 0d0748302c Smash function prologues on function destruction
Function prologues guard on Func* pointers rather on funcId.
This can cause a recycled Func* (with a different funcId) to
pass the prologue guard. Change it so that the Func* destructor
smashes the func prologue guard immediate.
2013-07-24 10:35:44 -07:00
Edwin Smith b9812e548a Change AttachLiteral to CopyString everywhere
This is a big codemod but has no effect; the actual change
was from D894412.
2013-07-24 10:35:44 -07:00
Edwin Smith 2e293e471e Eliminate AttachLiteralMode
Eagerly copy strings instead, getting us one step closer
to in-situ allocation for all StringDatas.
2013-07-24 10:35:44 -07:00
bsimmers 7aa354b270 Add build flags to control the region selector default
This will be used to run automated builds testing the new
region selectors.
2013-07-24 10:35:43 -07:00
Martin Matuska 1a5cc943e5 fix HHVM compilation on FreeBSD
- fix HHVM compilation on FreeBSD

Closes #874
2013-07-24 10:35:43 -07:00
mwilliams a946a8eb35 Get rid of TimeoutThread(s)
Use timer events instead. A side effect is that we now
support timeout in client mode. We also get much more
accurate timeouts. Previously starting a server with
a timeout of 4s, and GETing an endpoint that just looped,
would timeout somewhere between 3.5(!) and 8 seconds. Now
it times out between 4.0001 and 4.02s.

This will also make fixing pagelet timeouts much easier.
2013-07-24 10:35:43 -07:00
Daniel Sloof 2ac92de922 simplexml fixes for text children and casting
- fixes text children count and bool cast of empty nodes
2013-07-24 10:35:42 -07:00
Paul Tarjan 961d3add9e php_strip_whitespace
Close to zend's. Needed for composer.

I can't move the real zend test over since we don't apply zend's calling convention to systemlib (yet).
2013-07-24 10:35:42 -07:00
Vanilla Hsu 159c001f24 support current_executable_path on FreeBSD
- add support for current_executable_path on FreeBSD

Closes #878
2013-07-24 10:35:41 -07:00
Paul Tarjan 1845ed29b8 put fb_lazy_lstat back in the JSON
I got overzealous in my vim macros. Editing this JSON file is hard, sorry.
2013-07-24 10:35:41 -07:00
Jordan DeLong ab9652c99a Fix weird assignment operators in ScannerToken and Token
Copy assignment operators should generally take const lvalue
references and return non-const lvalue references to the lhs.  It's
unclear why these don't (probably no reason), so fix it.
2013-07-24 10:35:41 -07:00
Jordan DeLong 7df1338063 Remove unused undef stuff in bytecode.cpp
Vestigial.
2013-07-24 10:35:40 -07:00
Jordan DeLong a466faf52d Implement more of php assert()
Adds support for string arguments to assert (outside of repo
authoritative mode), and support for ASSERT_QUIET_EVAL.
2013-07-24 10:32:26 -07:00
Jordan DeLong d709f1c6b1 Make fooIsPlausible functions take args by value
Also, checkTv is redundant now, since I added the refcount
assertions to tvIsPlausible earlier.
2013-07-24 10:32:26 -07:00
Jordan DeLong e250fd6336 Implement bitwise negation outside of Variant 2013-07-24 10:32:26 -07:00
Jordan DeLong 5732b1c491 Remove tvReadCell; use cellDup, sometimes with tvToCell instead
This function used memcpy on TypedValues where it doesn't
know the storage location, which is dangerous if the target lives in a
HphpArray (or anything else that uses m_aux).  It also just seems like
it's now an unnecessary/redundant entry point in the typed value API.
Several uses of it are on things that can't be KindOfRef anyway (I
fixed constants, but where I wasn't sure I used tvToCell first).
2013-07-24 10:32:25 -07:00
mwilliams b400bfb015 Add an override for CoreFileSize
If present, CoreFileSizeOverride overrides the setting of CoreFileSize.
2013-07-24 10:32:25 -07:00
Jordan DeLong 0992cadf6f Implement inc/dec outside of variant 2013-07-24 10:32:25 -07:00
Paul Tarjan 5b367ac44a use all alias for travis
we want to run all suites, so lets let the test framework decide what that means
2013-07-23 16:42:21 -07:00
Martin Matuska 01858fbdce Remove inappropriate filter file from tests 2013-07-23 14:31:18 -07:00
bsimmers ae39c7330e Fix AtomicVector::ensureSize
I should've used unique_ptr::release() instead of unique_ptr::reset(),
but I decided to stop using unique_ptr altogether since gcc generated nicer
code without it. I also eliminated a redundant load of m_next.
2013-07-23 11:44:33 -07:00
Altan Alpay 8457c6232d sprintf() (and thus usprintf, etc) is null-unsafe
Fixing a potential security flaw in sprintf() caused by string parameters
containing mid-string null values to cut off output string prematurely.

eg sprintf("[%s]", "a\0b") === "[a"
2013-07-23 11:44:33 -07:00
Herman Venter acd68c4899 Check that the names used in function name breakpoints are valid PHP identifiers
Breakpoints of the form func() used the same routine to scan names as breakpoints of the form filename:lineno. This meant that you could write something like obj->func() and not get an error message. To fix this I've added a validation routine that is invoked when it has been determined that a name is part of a function name.
2013-07-23 11:44:32 -07:00
Paul Tarjan 27473154bc remove unused builtin functions from hhvm 2013-07-23 11:44:32 -07:00
Paul Tarjan 42490349ef make stream_select return feof streams
Thankfully an easier change than I had hoped thanks to @sgolemon. This will hopefully let us run Symphony's `proc_open` wrappers.
2013-07-23 11:44:32 -07:00
Paul Tarjan e7e0596ab0 remove default boolean params from File::TranslatePath
Most callsites use the defaults, and I can't figure out which callsites should and should not use it. Lets just have different functions for each use-case.
2013-07-23 11:44:31 -07:00
Paul Tarjan 22ec82a1af make include path work with stream wrappers
For phars, I need

  include "phar://some/file.phar/sub/file.php"

to work. I'm trying not to hurt the common path of using files.
2013-07-23 11:44:31 -07:00
Paul Tarjan 15b04a6097 delegate some syscalls to the stream wrappers
Needed for phars. People are doing

  file_exists('phar://a.phar/b.php');

I didn't do all syscalls like `chmod` or `symlink`. Think I should bite the bullet, or do it piecemeal when needed?
2013-07-23 11:44:31 -07:00
Paul Tarjan 9ce7792d8d implement RecursiveArrayIterator
I went through all the tests that mentioned this and looked at them. All of them don't pass because of other missing SPL problems not related to this class (and this class is simple so I wouldn't assume them to blame to it).

Closes #766
2013-07-23 11:44:30 -07:00
Jordan DeLong 10dacc2b44 Change hasThis to check ActRec::m_this & 1 again
It was checking & 3, and I couldn't figure out why.  It looks
like it was introduced probably accidentally by D498715.
2013-07-23 11:44:30 -07:00
Jordan DeLong 94703af1f4 Use ExtraData for LdCtx's compile-time Func parameter 2013-07-23 11:44:29 -07:00
Jordan DeLong 5c569b9d9e Tweaks to AllocObjFast relating to allocating extension classes
When there's an instance ctor, it's not necessary to do the
memcpy for properties or other ObjectData-initialization duties (the
instance ctor does this).  Also, use extra data for the compile-time
constant Class*.
2013-07-23 11:44:29 -07:00
Mike Magruder 8283969d81 Don't serialize cppext instances unless they opt-in, and pass the class name for the debugger
Most CPP extension classes don’t think about serialization, and some require more initialization than the default contractor provides. The result is that on deserialization we end up with a partially initialized object, and undefined behavior after that.

Modified the serializer to emit __PHP_Unserializable_Class instead, and just the class name for the debugger case. Modified the deserializer to create a __PHP_Unserializable_Class, too, if we are given a string with a CPP extension instance in it, so we're safe on both sides. I do not raise a warning; the results are pretty clear, I think, and it's also unlikely that most such warnings could (or should) be corrected. Finally, I also removed the odd behavior of emitting "dummy" classes for Closure and Continuation. I found no use of these in any source tree. Closure had no implementation at all, and Continuation had an implementation that simply raised a fatal on any method call. Thus we can safely assume that even if someone was serializing one of these types, they were receiving an object that was useless to them, or would fatal. So I believe this transformation is safe.
2013-07-23 11:44:16 -07:00
Daniel Sloof 77fb706e57 fix build error on OSX
- fix typo in embedded_data.cpp
2013-07-23 11:44:15 -07:00
aravind 6decb7dcc5 Fix build 2013-07-23 11:44:15 -07:00
Edwin Smith 27e29de6f4 Move _count to offset 12, and rename to m_count.
This allows us to swap TypedValue.m_type and m_aux, which puts
m_type at offset 8 and simplifies the necessary code for passing
TypedValue by value.  It also makes the m_type and m_data fields
of TypedValue contiguous.
2013-07-23 11:44:14 -07:00
aravind 95664338cb Revert "Treadmill for shared variants" 2013-07-23 11:44:12 -07:00
Mirek Klimos 62955d0af1 EmitterVisitor::emitPostponedMeths refactorization
EmitterVisitor::emitPostponedMeths was terribly long and disorganized.
Let's split it into more methods that can be later reused for emitting
generator body in FuncEmitter.
2013-07-23 11:44:11 -07:00
Edwin Smith 4864526172 Add NEWS files
initial files for release notes.
2013-07-23 11:44:11 -07:00
bsimmers 40cbd52dec Increase the starting size for the funcId AtomicVector
Sounds like there might be a bug in the growing logic. This
is just a stopgap until I get a real fix.
2013-07-23 11:44:11 -07:00
aravind 3606603fbd Revert "clean up SharedMap" 2013-07-23 11:44:08 -07:00
mwilliams f57bc3bf88 Revert "Delete GlobalCache" 2013-07-23 11:44:05 -07:00
aravind 58c4c797c5 Revert "Remove the SharedVariant pointer from StringData." 2013-07-23 11:44:01 -07:00
mwilliams 236f9d427c Revert "IterInit, IterInitK, IterNet and IterNextK specializations and guards" 2013-07-23 11:43:56 -07:00
bsimmers 858caa32d1 Maintain a mapping from funcId -> Func*
This diff adds AtomicVector (see comment in atomic_vector.h
for what it is) and uses it to maintain a mapping from funcIds to the
corresponding Func*. This is then used in sktrace instead of
curUnit(), since curUnit() isn't guaranteed to be the Unit the SrcKey
in question came from.
2013-07-23 11:37:12 -07:00
Edwin Smith a9479c7059 Eliminate CreateLvalPtr and GetLvalPtr
HphpArray::CreateLvalPtr does the same thing as LvalStr().  SharedMap
and NameValueTableWrapper::CreateLvalPtr just fatal, and aren't called
anyway.  GetLvalPtr is only called from one place which suppresses COW
and thus can also be done with nvGet, leaving getLvalPtr dead.
2013-07-22 11:34:12 -07:00
Ben Maurer ef1e94eee2 Only let one thread fadvise at a time
On Linux, fadvise forces unwritten pages to be flushed to disk before
returning. This means that under heavy disk IO, all threads could be
waiting on the fadvise call.

This diff uses atomic operations to ensure that only one thread can
do IO at any given time. In addition, it makes any fadvise calls
tail the end of the file by 1 MB. This reduces the chance that
fadvise will trigger IO at all.
2013-07-22 11:34:12 -07:00
Owen Yamauchi 9d5b8a9d5b Delete some dead code in FileScope
hphpc relic. I discovered this while working on $GLOBALS-in-HphpArray.
2013-07-22 11:34:11 -07:00
bsimmers 75751d201c Run object destructors before clearing autoload handler
Our request shutdown procedure cleared the autoload handler
before running destructors of any remaining objects. This was causing
fatals when some of those destructors tried to use a
class/function/constant that hadn't already been autoloaded.
2013-07-22 11:34:11 -07:00
Edwin Smith 1140d2f313 Rename typedef Var to Ref (its a reference)
And, several helper functions with the prefix "var" were changed
to the prefix "ref".  I reworded the bytecode spec; the flavor letter
for PHP references is still 'V', but I reworded parts of it to use
the term 'pointer' instead of 'reference' in places where reference
was too overloaded.  Renamed 'var' to 'ref' throughout.
2013-07-22 11:34:11 -07:00
Edwin Smith 7ad09ea866 Specialize vector & generic copies in HphpArray
This is some carnage left over from the Vector & devirtualize-ArrayData
work. Several places I left the original call to copyImpl(), where a
more specific call would have been ok.  In one place, I called the wrong
function, which would assert in debug and potentially crash in opt.
2013-07-22 11:34:11 -07:00
Paul Tarjan 213496f479 fix gzfile_basic.php
This test failed on tuseday from a file race. Some other test uses the same name. I also preemptively fixed another one I saw.
2013-07-22 11:34:10 -07:00
Dario Russi f2f631c163 IterInit, IterInitK, IterNet and IterNextK specializations and guards
Specialize IterInit and IterInitK after collection gurads and specialize IterNext and IterNextK after iter guard for collections and array
2013-07-22 11:34:10 -07:00
Jordan DeLong e28e3f205e Allow using ExtraData-supplied immediates in native-calls.cpp
Ports CreateCont* opcodes to use extra data for their
compile-time constants as a test case.
2013-07-22 11:34:10 -07:00
Jordan DeLong 6eaa0bb2f0 Verifier: always verify in debug builds
Let's prevent the verifier from bitrotting.
2013-07-22 11:34:09 -07:00
Edwin Smith 7204d561e5 Devirtualize ArrayData part 2
Convert remaining virtual methods to static methods dispatched
by kind.  This makes ArrayData a non-virtual class, so shuffle
fields and adjust static_asserts.
2013-07-22 11:34:09 -07:00
Edwin Smith 4f292ebb7f Fixed broken build from unused local variable.
that's it
2013-07-22 11:34:09 -07:00
Edwin Smith 49915fe2e6 Devirtualize ArrayData part 1
Moves about half of ArrayData virtual methods to g_array_funcs as
static functions instead of virtual functions.  This is mostly a
mechanical factor, except a handful of methods that are specialized
for Vector instead of generic HphpArray.
2013-07-22 11:34:09 -07:00
Sean Cannella acf4bf6487 Enable additional compiler warnings for gcc 4.7.1
Add compiler warnings to our build that are part of OSS to
catch them earlier.
2013-07-22 11:34:08 -07:00
Sean Cannella 739ffb3b24 OSX warnings (last batch to enable 4.7.1 warnings)
- fix last batch of warnings
2013-07-22 11:34:08 -07:00
Owen Yamauchi 68202e773c Delete GlobalCache
Pulling the trigger; it's unused post-tx64. This diff preserves the
ability to mark units as merge-only when the pseudomain only contains
assignments to known globals. When the unit is being merged, the set
operation goes directly to the global varenv instead of through the
targetcache (GlobalCache stored pointers into the global varenv's
NameValueTable).

Supersedes D891179 -- I was overly aggressive in that one.
2013-07-22 11:34:08 -07:00
Jan Oravec 7cd2bb8c42 Use Cell instead of TypedValue whenever possible
Most of the values stored in TypedValue in ext_asio are always Cells.
Let's use Cell type alias to improve code readability, pass them by
reference where null is not allowed and use Cell-specific functions
from tv_helpers.h.
2013-07-22 11:34:07 -07:00
Joel Marcey e6a11355a1 Implement PHP_BINARY PHP core predefined constant
Implement PHP_BINARY PHP core predefined constant. PHPUnit uses this constant in its self-test suite, causing many of them to fail on HHVM (possibly only because of the lack of this constant). Try to ninitially implement in such a way that it can be nimble enough for open-source, cross platform.
2013-07-22 11:34:07 -07:00
Joel Marcey b951f3b42d Implement json_last_error for PHPUnit
PHPUnit calls json_last_error. We need to implement it. Also implemented a simple json_last_error_msg to bring it up to 5.5 parity in that regard. This current implementation does not bring all the json zend tests to passing. But 2 out of the 22 bad tests now pass. And, this allows the PHPUnit self test to run as well.
2013-07-22 11:34:07 -07:00
Paul Bissonnette e9a9050451 OpDiv in codegen
added OpDiv to codegen if at least one operand is a double
2013-07-22 11:34:07 -07:00
Herman Venter 736f997ba8 Use PHP test framework for testing hphpd in sandbox server mode
Debugger tests that run hphp in non local mode (i.e. with the "-h some-server:some-port" option specified) currently use a clunky specialized C++ test harness that invokes PHP scripts that talk to the debugger client via the obsolete client API. This revision moves those tests to the new PHP only framework. The debugger client is now controlled by piping in commands, just like the other debugger tests. The main difference is that the debugger client is connected to a server instance and a separate PHP driver is used to load the server, load the client, and then load pages from the server so that the client can hit breakpoints. It also checks that the client can respond to ctrl-c by actually sending a SIGINT signal to the client process.
2013-07-22 11:34:06 -07:00
Paul Tarjan 53c7d78eea make socket test less flakey (hopefully)
I keep seeing problems with this test. Lets see if opening less sockets helps? The last few have failed on `socket_get_option($s, SOL_SOCKET, SO_TYPE)` which this does't fix though...
2013-07-22 11:34:06 -07:00
Guilherme Ottoni 0ae5908b61 Eliminate unconditional jump from main trace to exit trace before DCE
I ran into this problem with the region JIT.  Without this fix, an
IncRef may appear to be dead in the main trace during ref-counting
optimization (performed along with DCE).
2013-07-22 11:34:06 -07:00
Jan Oravec 87fa04b2f2 tv{Cell,Var}As*(TypedValue*) -> {cell,var}As*({Cell,Var}&)
Make tv{Cell,Var}As* take {Cell,Var} instead of TypedValue. Take them by
reference instead of by pointer.
2013-07-22 11:34:05 -07:00
Paul Tarjan 4e86ef19fc actually call o_toBoolean when casting to a bool - take 2
Redoing the diff. The original was breaking perflab, I want to see why (it worked for me, but without the `movb` change, maybe that was it).
2013-07-22 11:34:05 -07:00
mwilliams da5b2a2be2 Fix convenience test name matching
It used to lookup the longest initial sequence that contained
no slashes, so that eg:

  cd hphp/test
  ./run quick/SetM.php

Would run all the quick tests
2013-07-22 11:34:05 -07:00
Mike Magruder 4048565e87 Ensure flow control commands don't remove internal breakpoints set by real breakpoints
A real breakpoint makes entries in the breakpoint filter for all offsets at the given line. Various flow control commands will also use the breakpoint filter to add and remove temporary "internal breakpoints" required during the flow operation. Ensure that we never remove a breakpoint filter entry if there was already one there due to a breakpoint (or really  any other reason).
2013-07-22 11:34:05 -07:00
Mike Magruder 3231abf20a Add option to extend the time we'll wait before dropping into the dummy sandbox on debugger signals
When the proxy's signal polling thread gets a signal from the debugger client, it would normally wait one second for another thread to recognize and consume the signal. This is pretty reasonable, but with a debug build on a heavily loaded system it's very rarely possible for one second to not be long enough. Added a runtime option to extend this, and set it to 3s for the existing debugger server tests.
2013-07-22 11:34:04 -07:00
Sara Golemon 285b9e1d59 Add jemalloc and libintl include dirs to path
Remove bad defines for jemalloc on macosx
2013-07-20 08:44:51 -07:00
Sara Golemon 67a5b35892 Normalize newlines when doing expectf comparison in test/run
Newlines in expectf files don't necessarily match
newlines output by tests.  In the case of the bug55273 test,
the expectf file has unix (\n) newlines, but chunk_split()
produces DOS (\r\n) newlines by default.  This pattern
normalizes all expected newlines to accept unix, DOS, or old-style
Mac (\r) newlines.
2013-07-19 12:57:30 -07:00
Sara Golemon 65a6125580 Match PHP's numeric type conversion rules for math functions
Null/Bool/Object get converted to numeric values.
Touches abs(), floor(), ceil(), and round().
2013-07-19 12:57:30 -07:00
Sara Golemon 825cb52060 Fix parse_url()
Bug#54180 - Fragments containing '?'
Do not throw a notice on bad URLs
Add 'port' to return value after 'host', not at end of array
2013-07-19 12:57:29 -07:00
Paul Tarjan 38330353f6 warning on bad chdir
matches zend
2013-07-19 12:57:29 -07:00
Daniel Sloof cadddcd0d3 enable ServiceData on OSX
- re-enable servicedata on OSX now that jemalloc is fixed

Closes #865
2013-07-19 12:57:29 -07:00
Paul Bissonnette 1227cda52e Fixing bug with IterBreak assembler
Was failing to push iterator ID along with type in assembler.
2013-07-19 12:57:28 -07:00
Sean Cannella f319a3c029 gcc 4.7.1 unused-variable warnings
- fix unused variable warnings from OSS
2013-07-19 12:57:28 -07:00
mwilliams 76aed9f150 Empty loops need to check surprise flags
We didnt count a brach to itself as a backward branch.
Also, there seemed to be a signed vs unsigned issue with IterBreak.
2013-07-19 12:57:28 -07:00
Edwin Smith 1e3f2c2864 Remove checkExist option to ArrayData::lval()
It appears to be a leftover optimization that only applied to HPHPC,
which is gone now.
2013-07-19 12:57:27 -07:00
Guilherme Ottoni f107113ed3 Remove handling for const Bools that are neither 0 nor 1
It looks like whatever was introducing these has been fixed.
2013-07-19 12:57:27 -07:00
Bert Maher abca91e0fa Exit early during checkInvariants rather than do the O(N) loop.
This loop is useful for debugging arrays but is too slow for
general use, so we'll just "return true" before it and leave it in
place for offline use.
2013-07-19 12:57:27 -07:00
Owen Yamauchi 877c8ee9ec Minor cleanup of break/continue emission
Since variable break/continue is gone, we don't need this jonx anymore,
since the target of any break or continue is statically known. The
regular break/continue handling deals with this case appropriately.
2013-07-19 12:57:26 -07:00
Edwin Smith 353b33928b Make ArrayKind a regular enum
We use ArrayKind as a simple unsigned integer, its an index, we do
range-based comparisons, and in the future we'll likely do bit-ops
for fast sub-kind tests.  Just be honest that this is an old-school enum.
2013-07-19 12:57:26 -07:00
Sara Golemon 26a024296d Travis configure script need to have an up to date package list 2013-07-18 17:42:52 -07:00
Daniel Sloof c494c3a145 Don't use "echo -n" in /bin/sh scripts on MacOSX
The shell builtin implementation of echo on MacOSX
doesn't respect the -n flag.  This is the only usage of it
in our stack so far and we can avoid it by hiding the generated
token from the linter in a different way.
2013-07-18 17:28:44 -07:00
danslo 079dc468ca Comments are not SimpleXML element children
- Comments should not be counted as node children

Closes #863
2013-07-18 17:28:44 -07:00
Sean Cannella e5fc6d56f4 Document known limitation with PHP setlocale()
- Github contributor @karpa13a found and requested this issue be documented

Closes #860
2013-07-18 17:28:44 -07:00
Sean Cannella db987b4a4d clean up gcc 4.7.1 warnings on OSX
- cleans up new warnings
2013-07-18 17:28:43 -07:00
Edwin Smith 608df352de HphpArray Vector specializations
Introduces a new m_kind for vector-shaped HphpArray instances.
A vector has integer indexes in the range [0..size), and no
tombstones.  Internally it does not store the integer keys or
hashtable, although this version still allocates space for it.
2013-07-18 17:28:43 -07:00
Paul Tarjan 0335e335b7 build setAccessible
This implementation feels a bit haphazard with all the forces in the `o_*`. Is this stuff all changing dario?
2013-07-18 17:28:42 -07:00
Mirek Klimos 90b7170582 Remove Continuation from local 0
No emitted bytecode relies on Continuation being stored in local 0
anymore. Stop using local 0 for this purpose and compute offset
to the Continuation at JIT time. 16 bytes of memory freed.

At this point all locals of Continuation construction wrapper share the
same indices with their respective locals of Continuation body, which
should allow further optimizations.
2013-07-18 17:28:42 -07:00
Mirek Klimos f11bab46b7 Eliminate Continuation in local 0: JIT
The the code is being translated, we statically know offset of
Continuaton from its ActRec. Use this knowledge to emit data fetches
relative to ActRec rather than relative to Continuation loaded from
local 0.
2013-07-18 17:28:42 -07:00
huzhiguang 506329b7ce error_log add message_type=3 function
add f_error_log message_type=3 function
hhvm defult error_log message_type 0,so it can't support user-defind error_log mode(message_type=3)

Closes #831

Github: https://github.com/facebook/hiphop-php/pull/831
2013-07-18 17:28:41 -07:00
bsimmers 4665b068d4 Initial tracelet region selector
This diff renames the Tracelet -> RegionDesc conversion mode to
"legacy" (since it's going away eventually) and changes "tracelet" to use the
new region selection mode. It attempts to select a region that will be the same
length as what Translator::analyze would come up with, using HhbcTranslator for
all of the type flow logic. It generates longer tracelets in some cases due to
more precise type information. Once this new mode is no longer a perf
regression it can become the new default, replacing all the code in
Translator::analyze and the "legacy" region mode. This version doesn't support
inlining or tracking of known Func*s; those will come in later diffs.
2013-07-18 17:28:41 -07:00
Paul Tarjan c9b0ebd674 change get_resource_type() to match zend
in composer.phar they test `get_resource_type` and make sure it matches this string. This just seemed like a bug.
2013-07-18 17:28:40 -07:00
Paul Tarjan 22f908f1d7 add some more constants that zend defines
`composer.phar` was using these, so we should probably define them. I made them match what we were giving for `PHP_VERSION`.
2013-07-18 17:28:40 -07:00
Mike Magruder 601ca57f53 Cleanup debugger client shutdown
The exit path for the debugger client has always been a little odd. We'd call a shutdown function which would destroy the client, then later call a stop function which would first make a new client, then stop it, then that one would get destroyed later. Made it so we stop and destroy just one client.
2013-07-18 17:28:40 -07:00
Herman Venter ee2cd8d32e Do not evaluate breakpoint conditions during stepping.
Flow control commands should not evaluate the conditions of conditional breakpoints when enabling and disabling breakpoints during stepping. Also, all breakpoints, rather than just the first matching breakpoint should be enabled/disabled.
2013-07-18 17:28:39 -07:00
Jordan DeLong 29dbaf3ae9 Remove assert on maxStackCells > 0
One of these was left over.
2013-07-18 17:28:39 -07:00
Mike Magruder 76fd23c2cb Remove rare flakieness from protocol tests
There was a race in the debugger protocol tests which send bad commands to the proxy and expect it to disconnect. If the proxy thread was fast enough it would mark the client as stopped, and we'd skip trying to get a new message after sending the bad command. This means missing one line of output in very rare cases. I've put in a wait to ensure that the client settles in the stopped state before continuing, to remove the race.
2013-07-18 17:28:39 -07:00
Owen Yamauchi 86eb82ec2f Fix break/continue parsing
This is exactly what Zend's parser does now. I'm a little sad about
adding the bool parameter, but all the checking code was exactly
duplicated otherwise, and that seemed like the worse alternative.

Fixes #854
2013-07-18 17:28:38 -07:00
mwilliams db130c83e1 Identify direct children of yield expressions
We want to be able to recognize them without knowing their
context.
2013-07-18 17:28:38 -07:00
Paul Bissonnette 0a111314bd Adding shift left and right to codegen
shift left and right in codegen
2013-07-18 17:28:37 -07:00
Kyle Delong a8e3321fbd HPHP/XHP: 'mixed' type in attribute declarations
We'd like to start using ##mixed## instead of ##var## for attribute types to be consistent with Hack. As a followup to this (once released), we would codemod all ##var## to ##mixed##.
2013-07-18 17:28:37 -07:00
Mike Magruder f3d5a8abb1 Allow ctrl-c during eval
A client couldn't break execution during eval. There used to be a lot of barriers to making that right, but I fixed most of them with a previous diff on unifying client-side event loops. Now the only barrier was that a server-side thread processing an interrupt was blocking the signal polling thread by holding a mutex while processing the interrupt. Changed to set a flag to disable polling when starting to process the interrupt (and unsetting it when done), while still synchronizing with the signal polling thread to ensure only one thread is sending the client messages at a time. Added logic to re-enable polling while executing PHP for eval, print, etc. Plumbed the proxy thru to the point where we check the clause on conditional breakpoints, too, since that's the third (and final) place we do this.
2013-07-18 17:28:36 -07:00
Herman Venter b03f72d185 Only one break point can be set per file when running against a server
When the client sends a list of breakpoints over to the server, the logic that applies the breakpoints as soon as a file is loaded is broken. It stops looking at breakpoints as soon as it finds the first one. It should carry on and look at all of them.
2013-07-18 17:28:36 -07:00
Edwin Smith 721f89b890 Flatten directories under runtime/base
This moves runtime/base/*/* to runtime/base, and fixes paths.
2013-07-18 17:28:35 -07:00
bsimmers a9e58686ab Pull Translator's translate* methods into a separate class
This diff creates IRTranslator, which creates and uses an
HhbcTranslator to implement the translate* methods. It can be used
independently of Translator or TranslatorX64 (it isn't yet but my next
region compiler diff uses it). I also moved a bunch of methods out of
inappropriate classes and changed the type guard/assert methods in
HhbcTranslator to use RegionDesc::Location instead of Transl::Location
and fixes a local tracking issue in translateRegion.
2013-07-18 17:28:34 -07:00
Jordan DeLong 43d8497245 Translate BitNot on doubles 2013-07-18 17:28:34 -07:00
Benjamin Strahs 8ce9231f1b Fix DOMDocument UTF-16 parsing
We should be using xmlCreateMemoryParserCtxt for in-memory XML documents because it correctly handles UTF-16 encoded strings.
2013-07-18 17:28:33 -07:00
Owen Yamauchi 4cea6506e6 Get rid of NameValueTableWrapper, part 2 of 3
Part 2: getting rid of NVTW for initializing nonscalar static
properties. This is slightly messier than the equivalent for nonstatic
properties.
2013-07-18 17:28:33 -07:00
Sara Golemon 96151050af Update folly 2013-07-18 17:28:32 -07:00
Sara Golemon 5c93a5fe40 Prevent buffer overrun during iopBitOr on string args
"foo" | "f" is meant to yield a string of length
max(strlen("foo"), strlen("f")) by bitwise ORing each byte
of one string against the corresponding byte of the other.

When the strings are of differing lengths, however, we get unknown
garbage data from past the end of the buffer.  This data is
often '\0', however under memory pressure we can get any
value and the behavior becomes undefined.
2013-07-18 17:28:22 -07:00
Keith Adams bbcf1a2db3 Make Asm::code private.
Having everybody and their uncle reading and writing fields out
of a.code and stubs.code was making assembler work hard. This replaces most
reads with accessors, and all writes with structured friends of
X64SAssembler.
2013-07-15 18:13:31 -07:00
Edwin Smith c4e406b62f Move runtime/base/server to runtime/server
This is an incremental step towards moving it all the way
to hphp/server.  This flattens base but doesn't untangle
the server files from lib_hphp_runtime
2013-07-15 18:13:25 -07:00
Keith Adams d3673cad74 Make it possible to wait for gdb on crash.
Often I happen not to be running under a debugger when a
crash occurs. In my debugging workflow, I'd prefer our crash handler to
preserve the broken state and spin waiting for gdb to attach rather than
dump core, attempt its own little sad stacktraces, etc. Driven via a
default-false config flag.
2013-07-15 17:35:33 -07:00
Mike Magruder f3e19a5dfa Fix machine force attach
I broke the operation of CmdMachine when we attach with the force flag with https://phabricator.fb.com/D851880. I consolidated some error handling logic around broken connections, etc., and in particular pulled throwing of an exception into forceQuit(). I failed to realize there was a single call site of forceQuit() that did not in fact throw an exception afterwards… the logic underneath of force attach. Switching the forceQuit() call there to stop() replaces the logic that was there previously, and restores the behavior.
2013-07-15 17:35:32 -07:00
aravind b5f608b942 always_assert when we run out of TC space
Makes debugging easier.
2013-07-15 17:35:32 -07:00
Herman Venter 10f93d4828 Do not report start, end and psp breakpoints as unbound when connected to a sandbox.
break start/end/psp currently always report themselves as unbound. If the client is connected to a sanbox, these should instead be treated as bound. Also, break clear all currently removes breakpoints without running their destructors in the right order, which causes the break point counter to not reset to 1.
2013-07-15 17:35:31 -07:00
Daniel Sloof 9904554f66 fix issue with finding embedded systemlib on OSX
- make finding embedded systemlib data path independent on OSX
2013-07-15 17:35:27 -07:00
Mike Magruder f051e2fe04 Don't go back to the interpreter after the end of pseudo main when debugging
Fix a long-standing bug where if you step off of the end of pseudo main we'd segfault in the interpreter loop. To get this we have to have a breakpoint in the final TC in pseudo main, and have that called from another TC, then Step or Next off the end. We'd end up with a PC of zero after the ret, which makes sense, but the logic after interpreting a block of code to stay in the interpreter when debugging was blind to this case.
2013-07-15 17:34:47 -07:00
Edwin Smith 9b6bf426b9 Move runtime/base/array/* up one level.
Also rename array_inline.h to array_data-inl.h
2013-07-15 17:34:47 -07:00
Sean Cannella 7d07873817 OSX warnings
- fix OSS warnings
2013-07-15 17:34:42 -07:00
Joel Marcey ffab2c17f8 Implement SplObjectStorage::getInfo()
Implement SplObjectStorage::getInfo(). PHPUnit requires this method.
2013-07-15 15:46:32 -07:00
Sanjeev Singh 75397a10c7 Initial rough draft of xhpast2, a replacement for xhpast
The goal of this diff is to clean up the current work-in-progress and check
it in so that others may contribute if they have time.

The program currently outputs the HHVM tree as well as the xhpast-like
json, for ease of debugging. There is a little helper program jsonpretty.py
to make the trees more readable, e.g.

_build/dbg/hphp/util/parser/xhpast/xhpast2 <some php file> | hphp/util/parser/xhpast/xhpast2/jsonpretty.py
2013-07-15 15:46:32 -07:00
Edwin Smith 746862246f Fix typos from "Remove do/while(0) trick in iopFCallBuiltin macros"
s/-1/-i/
Add missing \
2013-07-15 15:46:28 -07:00
Jordan DeLong a28b21c191 Remove do/while(0) trick in iopFCallBuiltin macros
It doesn't really make sense in this context.  Also pushed
the if statement down into the CASE macro for now and fixed some
indentation.
2013-07-15 15:46:28 -07:00
Jordan DeLong 0c489492dc Remove array_iter_foo functions from Variant and VRefParam @override-unit-failures
Pretty much just moves them to their only callers in
ext_array.
2013-07-15 15:46:27 -07:00
Jordan DeLong 8e3ee5a87f Use stringToNumeric in tv_comparisons
I like this api slightly better than passing in multiple
output refs, but when I added I didn't change these so I could see
perflabs separately.
2013-07-15 15:46:27 -07:00
Jordan DeLong 1c764cabf0 Remove redundant function in Array
get() and getArrayData() do the same thing.
2013-07-15 15:46:27 -07:00
22491 arquivos alterados com 579583 adições e 252165 exclusões
+8 -4
Ver Arquivo
@@ -31,8 +31,8 @@ hphp.log
/hphp/runtime/tmp/run
/hphp/runtime/tmp/run.sh
/hphp/runtime/tmp/libtest.so
/hphp/hphp_build_info.cpp
/hphp/hphp_repo_schema.h
/hphp/hphp-build-info.cpp
/hphp/hphp-repo-schema.h
/hphp/hhvm/gen
/hphp/hhvm/hhvm
@@ -41,8 +41,12 @@ hphp.log
/hphp/runtime/ext/*.ext_hhvm.h
/hphp/runtime/ext/*/*.ext_hhvm.cpp
/hphp/runtime/ext/*/*.ext_hhvm.h
/hphp/runtime/base/builtin_functions.cpp.ext_hhvm.cpp
/hphp/runtime/base/builtin_functions.cpp.ext_hhvm.h
/hphp/runtime/ext_zend_compat/*/*.ext_hhvm.cpp
/hphp/runtime/ext_zend_compat/*/*.ext_hhvm.h
/hphp/runtime/ext_zend_compat/*/*/*.ext_hhvm.cpp
/hphp/runtime/ext_zend_compat/*/*/*.ext_hhvm.h
/hphp/runtime/base/builtin-functions.cpp.ext_hhvm.cpp
/hphp/runtime/base/builtin-functions.cpp.ext_hhvm.h
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.cpp
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.h
+17 -4
Ver Arquivo
@@ -1,13 +1,26 @@
language: cpp
compiler:
- gcc
before_script:
- ./configure_ubuntu_12.04.sh
- TRAVIS=1 ./configure_ubuntu_12.04.sh
# for some tests
- sudo locale-gen de_DE && sudo locale-gen zh_CN.utf8 && sudo locale-gen fr_FR
- HPHP_HOME=`pwd` make -j 8
script: hphp/hhvm/hhvm hphp/test/run quick slow zend
- HPHP_HOME=`pwd` make -j 6
# Test suites take longer to run in RepoAuthoritative mode (-r) than normal so
# split out the -r from normal runs and further split the -r runs by suite to
# avoid the possibility of slower machines exceeding the 50 minute test timeout
env:
- TEST_RUN_MODE="-m jit all"
- TEST_RUN_MODE="-m interp all"
- TEST_RUN_MODE="-m jit -r quick slow"
- TEST_RUN_MODE="-m interp -r quick slow"
- TEST_RUN_MODE="-m jit -r zend"
- TEST_RUN_MODE="-m interp -r zend"
script: hphp/hhvm/hhvm hphp/test/run $TEST_RUN_MODE
notifications:
irc: "chat.freenode.net#hhvm"
+13
Ver Arquivo
@@ -0,0 +1,13 @@
if (EDITLINE_LIBRARIES AND EDITLINE_INCLUDE_DIRS)
set (Editline_FIND_QUIETLY TRUE)
endif (EDITLINE_LIBRARIES AND EDITLINE_INCLUDE_DIRS)
find_path(EDITLINE_INCLUDE_DIRS NAMES editline/readline.h)
find_library(EDITLINE_LIBRARIES NAMES edit)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Editline DEFAULT_MSG
EDITLINE_LIBRARIES
EDITLINE_INCLUDE_DIRS)
mark_as_advanced(EDITLINE_INCLUDE_DIRS EDITLINE_LIBRARIES)
+27
Ver Arquivo
@@ -0,0 +1,27 @@
# - Try to find libdl
# Once done this will define
#
# LIBDL_FOUND - system has libdl
# LIBDL_INCLUDE_DIRS - the libdl include directory
# LIBDL_LIBRARIES - Link these to use libdl
# LIBDL_NEEDS_UNDERSCORE - If extern "C" symbols are prefixed (BSD/Apple)
#
find_path (LIBDL_INCLUDE_DIRS NAMES dlfcn.h)
find_library (LIBDL_LIBRARIES NAMES dl)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDL DEFAULT_MSG
LIBDL_LIBRARIES
LIBDL_INCLUDE_DIRS)
SET(CMAKE_REQUIRED_LIBRARIES dl)
INCLUDE(CheckCSourceRuns)
CHECK_C_SOURCE_RUNS("#include <dlfcn.h>
void testfunc() {}
int main() {
testfunc();
return dyslm(0, \"_testfunc\") != (void*)0;
}" LIBDL_NEEDS_UNDERSCORE)
mark_as_advanced(LIBDL_INCLUDE_DIRS LIBDL_LIBRARIES LIBDL_NEEDS_UNDERSCORE)
+13
Ver Arquivo
@@ -0,0 +1,13 @@
if (LIBNUMA_LIBRARIES AND LIBNUMA_INCLUDE_DIRS)
set (LibNuma_FIND_QUIETLY TRUE)
endif (LIBNUMA_LIBRARIES AND LIBNUMA_INCLUDE_DIRS)
find_path(LIBNUMA_INCLUDE_DIRS NAMES numa.h)
find_library(LIBNUMA_LIBRARIES NAMES numa)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibNuma DEFAULT_MSG
LIBNUMA_LIBRARIES
LIBNUMA_INCLUDE_DIRS)
mark_as_advanced(LIBNUMA_INCLUDE_DIRS LIBNUMA_LIBRARIES)
-28
Ver Arquivo
@@ -1,28 +0,0 @@
#
# $Id$
#
# - Find libunwind
# Find libunwind
#
# LIBUNWIND_INCLUDE_DIR - where to find unwind.h and libunwind.h
# LIBUNWIND_LIBRARY - List of libraries when using libunwind
# LIBUNWIND_FOUND - True if libunwind found.
if(LIBUNWIND_INCLUDE_DIR)
# Already in cache, be silent
SET(LIBUNWIND_FIND_QUIETLY TRUE)
endif()
FIND_PATH(LIBUNWIND_INCLUDE_DIR libunwind.h)
if(NOT EXISTS "${LIBUNWIND_INCLUDE_DIR}/unwind.h")
message(FATAL_ERROR "libunwind.h found without matching unwind.h")
SET(LIBUNWIND_INCLUDE_DIR "")
endif()
FIND_LIBRARY(LIBUNWIND_LIBRARY unwind)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBUNWIND DEFAULT_MSG LIBUNWIND_LIBRARY LIBUNWIND_INCLUDE_DIR)
MARK_AS_ADVANCED(LIBUNWIND_LIBRARY LIBUNWIND_INCLUDE_DIR)
+61
Ver Arquivo
@@ -0,0 +1,61 @@
if(CMAKE_COMPILER_IS_GNUCC)
INCLUDE(CheckCSourceCompiles)
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40600
#error Need GCC 4.6.0+
#endif
int main() { return 0; }" HAVE_GCC_46)
if(NOT HAVE_GCC_46)
message(FATAL_ERROR "Need at least GCC 4.6")
endif()
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40700
#error Not GCC 4.7.0+
#endif
int main() { return 0; }" HAVE_GCC_47)
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40800
#error Not GCC 4.8.0+
#endif
int main() { return 0; }" HAVE_GCC_48)
endif()
set(FREEBSD FALSE)
set(LINUX FALSE)
if("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
set(FREEBSD TRUE)
endif()
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
set(LINUX TRUE)
endif()
if($ENV{CXX} MATCHES "icpc")
set(CMAKE_C_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -w")
set(CMAKE_CXX_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -w1 -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names")
else()
set(GNUCC_UNINIT_OPT "")
if(HAVE_GCC_47)
set(GNUCC_UNINIT_OPT "-Wno-maybe-uninitialized")
endif()
set(GNUCC_LOCAL_TYPEDEF_OPT "")
if(HAVE_GCC_48)
set(GNUCC_LOCAL_TYPEDEF_OPT "-Wno-unused-local-typedefs")
endif()
set(CMAKE_C_FLAGS "-w")
set(CMAKE_CXX_FLAGS "-fno-gcse -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names -Wno-error=array-bounds -Wno-error=switch -std=gnu++0x -Werror=format-security -Wno-unused-result -Wno-sign-compare -Wno-attributes ${GNUCC_UNINIT_OPT} ${GNUCC_LOCAL_TYPEDEF_OPT}")
endif()
if(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_C_FLAGS_RELEASE "-O3")
endif()
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
endif()
+58 -25
Ver Arquivo
@@ -17,6 +17,16 @@
include(CheckFunctionExists)
# libdl
find_package(LibDL)
if (LIBDL_INCLUDE_DIRS)
add_definitions("-DHAVE_LIBDL")
include_directories(${LIBDL_INCLUDE_DIRS})
if (LIBDL_NEEDS_UNDERSCORE)
add_definitions("-DLIBDL_NEEDS_UNDERSCORE")
endif()
endif()
# boost checks
find_package(Boost 1.48.0 COMPONENTS system program_options filesystem regex REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
@@ -38,10 +48,6 @@ if (LIBINOTIFY_INCLUDE_DIR)
include_directories(${LIBINOTIFY_INCLUDE_DIR})
endif()
# unwind checks
find_package(Libunwind REQUIRED)
include_directories(${LIBUNWIND_INCLUDE_DIR})
# iconv checks
find_package(Libiconv REQUIRED)
include_directories(${LIBICONV_INCLUDE_DIR})
@@ -91,13 +97,6 @@ set(CMAKE_REQUIRED_LIBRARIES)
# GD checks
find_package(GD REQUIRED)
if (WANT_FB_LIBMCC)
add_definitions(-DHPHP_WITH_LIBMCC)
message(FATAL_ERROR Need to add libmcc and libch for linking)
else ()
# nothing for now
endif()
find_package(LibXed)
if (LibXed_INCLUDE_DIR AND LibXed_LIBRARY)
include_directories(${LibXed_INCLUDE_DIR})
@@ -150,9 +149,6 @@ if (ICU_FOUND)
include_directories(${ICU_INCLUDE_DIRS})
endif (ICU_FOUND)
# (google heap OR cpu profiler) AND libunwind
FIND_LIBRARY(UNWIND_LIB unwind)
# jemalloc/tmalloc and profiler
if (USE_GOOGLE_HEAP_PROFILER OR USE_GOOGLE_CPU_PROFILER)
FIND_LIBRARY(GOOGLE_PROFILER_LIB profiler)
@@ -178,10 +174,30 @@ if (USE_GOOGLE_HEAP_PROFILER AND GOOGLE_PROFILER_LIB)
endif()
if (USE_JEMALLOC AND NOT GOOGLE_TCMALLOC_ENABLED)
FIND_LIBRARY(JEMALLOC_LIB jemalloc)
if (JEMALLOC_LIB)
message(STATUS "Found jemalloc: ${JEMALLOC_LIB}")
set(JEMALLOC_ENABLED 1)
FIND_LIBRARY(JEMALLOC_LIB NAMES jemalloc)
FIND_PATH(JEMALLOC_INCLUDE_DIR NAMES jemalloc/jemalloc.h)
if (JEMALLOC_INCLUDE_DIR AND JEMALLOC_LIB)
include_directories(${JEMALLOC_INCLUDE_DIR})
set (CMAKE_REQUIRED_INCLUDES ${JEMALLOC_INCLUDE_DIR})
INCLUDE(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("
#include <jemalloc/jemalloc.h>
int main(void) {
#if !defined(JEMALLOC_VERSION_MAJOR) || (JEMALLOC_VERSION_MAJOR < 3)
# error \"jemalloc version >= 3.0.0 required\"
#endif
return 0;
}" JEMALLOC_VERSION_3)
set (CMAKE_REQUIRED_INCLUDES)
if (JEMALLOC_VERSION_3)
message(STATUS "Found jemalloc: ${JEMALLOC_LIB}")
set(JEMALLOC_ENABLED 1)
else()
message(STATUS "Found jemalloc, but it was too old")
endif()
endif()
endif()
@@ -197,9 +213,6 @@ endif()
if (JEMALLOC_ENABLED)
add_definitions(-DUSE_JEMALLOC=1)
if (APPLE)
add_definitions(-DJEMALLOC_MANGLE=1 -DJEMALLOC_EXPERIMENTAL=1)
endif()
else()
add_definitions(-DNO_JEMALLOC=1)
endif()
@@ -259,8 +272,17 @@ include_directories(${NCURSES_INCLUDE_PATH})
find_package(PThread REQUIRED)
include_directories(${LIBPTHREAD_INCLUDE_DIRS})
find_package(Readline REQUIRED)
include_directories(${READLINE_INCLUDE_DIR})
# Either Readline or Editline (for hphpd)
find_package(Readline)
find_package(Editline)
if (READLINE_INCLUDE_DIR)
include_directories(${READLINE_INCLUDE_DIR})
elseif (EDITLINE_INCLUDE_DIRS)
add_definitions("-DUSE_EDITLINE")
include_directories(${EDITLINE_INCLUDE_DIRS})
else()
message(FATAL_ERROR "Could not find Readline or Editline")
endif()
find_package(CClient REQUIRED)
include_directories(${CCLIENT_INCLUDE_PATH})
@@ -335,6 +357,9 @@ endif()
if (APPLE)
find_library(LIBINTL_LIBRARIES NAMES intl libintl)
if (LIBINTL_INCLUDE_DIR)
include_directories(${LIBINTL_INCLUDE_DIR})
endif()
find_library(KERBEROS_LIB NAMES gssapi_krb5)
endif()
@@ -349,6 +374,10 @@ include_directories(${HPHP_HOME}/hphp)
include_directories(${HPHP_HOME}/hphp/system/gen)
macro(hphp_link target)
if (LIBDL_LIBRARIES)
target_link_libraries(${target} ${LIBDL_LIBRARIES})
endif ()
if (GOOGLE_HEAP_PROFILER_ENABLED OR GOOGLE_CPU_PROFILER_ENABLED)
target_link_libraries(${target} ${GOOGLE_PROFILER_LIB})
endif()
@@ -364,7 +393,6 @@ macro(hphp_link target)
endif()
target_link_libraries(${target} ${Boost_LIBRARIES})
target_link_libraries(${target} ${LIBUNWIND_LIBRARY})
target_link_libraries(${target} ${MYSQL_CLIENT_LIBS})
target_link_libraries(${target} ${PCRE_LIBRARY})
target_link_libraries(${target} ${ICU_DATA_LIBRARIES} ${ICU_I18N_LIBRARIES} ${ICU_LIBRARIES})
@@ -438,7 +466,12 @@ endif()
target_link_libraries(${target} afdt)
target_link_libraries(${target} mbfl)
target_link_libraries(${target} ${READLINE_LIBRARY})
if (READLINE_LIBRARY)
target_link_libraries(${target} ${READLINE_LIBRARY})
elseif (EDITLINE_LIBRARIES)
target_link_libraries(${target} ${EDITLINE_LIBRARIES})
endif()
target_link_libraries(${target} ${NCURSES_LIBRARY})
target_link_libraries(${target} ${CCLIENT_LIBRARY})
+43
Ver Arquivo
@@ -67,3 +67,46 @@ macro(MYSQL_SOCKET_SEARCH)
set(MYSQL_UNIX_SOCK_ADDR ${MYSQL_SOCK} CACHE STRING "Path to MySQL Socket")
endif()
endmacro()
function(embed_systemlib TARGET DEST SOURCE)
if (APPLE)
target_link_libraries(${TARGET} -Wl,-sectcreate,__text,systemlib,${SOURCE})
else()
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND "objcopy"
ARGS "--add-section" "systemlib=${SOURCE}" ${DEST}
COMMENT "Embedding systemlib.php in ${TARGET}")
endif()
# Add the systemlib file to the "LINK_DEPENDS" for the systemlib, this will cause it
# to be relinked and the systemlib re-embedded
set_property(TARGET ${TARGET} APPEND PROPERTY LINK_DEPENDS ${SOURCE})
endfunction(embed_systemlib)
# Custom install function that doesn't relink, instead it uses chrpath to change it, if
# it's available, otherwise, it leaves the chrpath alone
function(HHVM_INSTALL TARGET DEST)
get_target_property(LOC ${TARGET} LOCATION)
get_target_property(TY ${TARGET} TYPE)
if (FOUND_CHRPATH)
get_target_property(RPATH ${TARGET} INSTALL_RPATH)
if (NOT RPATH STREQUAL "RPATH-NOTFOUND")
if (RPATH STREQUAL "")
install(CODE "execute_process(COMMAND \"${CHRPATH}\" \"-d\" \"${LOC}\" ERROR_QUIET)")
else()
install(CODE "execute_process(COMMAND \"${CHRPATH}\" \"-r\" \"${RPATH}\" \"${LOC}\" ERROR_QUIET)")
endif()
endif()
endif()
install(CODE "FILE(INSTALL DESTINATION \"\${CMAKE_INSTALL_PREFIX}/${DEST}\" TYPE ${TY} FILES \"${LOC}\")")
endfunction(HHVM_INSTALL)
function(HHVM_EXTENSION EXTNAME)
list(REMOVE_AT ARGV 0)
add_library(${EXTNAME} SHARED ${ARGV})
set_target_properties(${EXTNAME} PROPERTIES PREFIX "")
set_target_properties(${EXTNAME} PROPERTIES SUFFIX ".so")
endfunction()
function(HHVM_SYSTEMLIB EXTNAME SOURCE_FILE)
embed_systemlib(${EXTNAME} "${EXTNAME}.so" ${SOURCE_FILE})
endfunction()
+25 -59
Ver Arquivo
@@ -1,5 +1,22 @@
include(Options)
if (APPLE)
set(HHVM_ANCHOR_SYMS -Wl,-u,_register_libevent_server)
else()
set(HHVM_ANCHOR_SYMS -Wl,-uregister_libevent_server)
endif()
set(HHVM_LINK_LIBRARIES
hphp_analysis
hphp_runtime_static
ext_hhvm_static
hphp_system
hphp_parser
hphp_zend
hphp_util
vixl neo
${HHVM_ANCHOR_SYMS})
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif()
@@ -8,29 +25,13 @@ IF(NOT DEFINED CMAKE_PREFIX_PATH)
message(STATUS "CMAKE_PREFIX_PATH was missing, proceeding anyway")
endif()
if(CMAKE_COMPILER_IS_GNUCC)
INCLUDE(CheckCSourceCompiles)
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40600
#error Need GCC 4.6.0+
#endif
int main() { return 0; }" HAVE_GCC_46)
if(NOT HAVE_GCC_46)
message(FATAL_ERROR "Need at least GCC 4.6")
endif()
endif()
set(FREEBSD FALSE)
set(LINUX FALSE)
if("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
set(FREEBSD TRUE)
endif()
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
set(LINUX TRUE)
# Look for the chrpath tool so we can warn if it's not there
find_program(CHRPATH chrpath)
IF (CHRPATH STREQUAL "CHRPATH-NOTFOUND")
SET(FOUND_CHRPATH OFF)
message(WARNING "chrpath not found, rpath will not be stripped from installed binaries")
else()
SET(FOUND_CHRPATH ON)
endif()
LIST(APPEND CMAKE_PREFIX_PATH "$ENV{CMAKE_PREFIX_PATH}")
@@ -42,6 +43,7 @@ if(APPLE)
endif()
endif()
include(HPHPCompiler)
include(HPHPFunctions)
include(HPHPFindLibs)
@@ -61,22 +63,6 @@ else()
message("Generating DEBUG build")
endif()
if(INFINITE_LOOP_DETECTION)
add_definitions(-DINFINITE_LOOP_DETECTION=1)
endif()
if(INFINITE_RECURSION_DETECTION)
add_definitions(-DINFINITE_RECURSION_DETECTION=1)
endif()
if(REQUEST_TIMEOUT_DETECTION)
add_definitions(-DREQUEST_TIMEOUT_DETECTION=1)
endif()
if(ENABLE_LATE_STATIC_BINDING)
add_definitions(-DENABLE_LATE_STATIC_BINDING=1)
endif()
if(DEBUG_MEMORY_LEAK)
add_definitions(-DDEBUG_MEMORY_LEAK=1)
endif()
@@ -93,10 +79,6 @@ if(HOTPROFILER)
add_definitions(-DHOTPROFILER=1)
endif()
if(HOTPROFILER_NO_BUILTIN)
add_definitions(-DHOTPROFILER_NO_BUILTIN=1)
endif()
if(EXECUTION_PROFILER)
add_definitions(-DEXECUTION_PROFILER=1)
endif()
@@ -129,22 +111,6 @@ add_definitions(-DHPHP_OSS=1)
# later versions of binutils don't play well without automake
add_definitions(-DPACKAGE=hhvm -DPACKAGE_VERSION=Release)
IF($ENV{CXX} MATCHES "icpc")
set(CMAKE_C_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -w")
set(CMAKE_CXX_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -w1 -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names")
else()
set(CMAKE_C_FLAGS "-w")
set(CMAKE_CXX_FLAGS "-fno-gcse -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names -Wno-error=array-bounds -Wno-error=switch -std=gnu++0x -Werror=format-security -Wno-unused-result -Wno-sign-compare")
endif()
IF(CMAKE_COMPILER_IS_GNUCC)
SET (CMAKE_C_FLAGS_RELEASE "-O3")
ENDIF()
IF(CMAKE_COMPILER_IS_GNUCXX)
SET (CMAKE_CXX_FLAGS_RELEASE "-O3")
ENDIF()
include_directories(${HPHP_HOME}/hphp)
include_directories(${HPHP_HOME}/hphp/lib/system/gen)
include_directories(${HPHP_HOME})
-9
Ver Arquivo
@@ -1,22 +1,13 @@
#set(CMAKE_BUILD_TYPE Debug)
option(ENABLE_LATE_STATIC_BINDING "Enable Late Static Binding" ON)
option(INFINITE_LOOP_DETECTION "Enable Infinite Loop Detection" ON)
option(INFINITE_RECURSION_DETECTION "Enable Infinite Recursion Detection" ON)
option(REQUEST_TIMEOUT_DETECTION "Enable Timeout Detection" ON)
option(ALWAYS_ASSERT "Enabled asserts in a release build" OFF)
option(DEBUG_MEMORY_LEAK "Allow easier debugging of memory leaks" OFF)
option(DEBUG_APC_LEAK "Allow easier debugging of apc leaks" OFF)
option(HOTPROFILER "Enable support for the hot-profiler" OFF)
option(HOTPROFILER_NO_BUILTIN "Don't consider builtins for the hot-profiler" OFF)
option(EXECUTION_PROFILER "Enable the execution profiler" OFF)
option(ENABLE_FULL_SETLINE "Enable full setline function for debugger and code-coverage" OFF)
option(WANT_FB_LIBMCC "want FB Memcache" OFF)
option(USE_JEMALLOC "Use jemalloc" ON)
option(USE_TCMALLOC "Use tcmalloc (if jemalloc is not used)" ON)
+18
Ver Arquivo
@@ -0,0 +1,18 @@
# Contributing to HipHop
We'd love to have your help in making HipHop better. If you run into problems, please open an [issue](http://github.com/facebook/hiphop-php/issues), or better yet, fork us and send a pull request.
If you want to help but don't know where to start, try fixing some of the [Zend tests that don't pass](hphp/test/zend/bad). You can run them with [hphp/test/run](hphp/test/run). When they work, move them to [zend/good](hphp/test/zend/good) and send a pull request.
All the open issues tagged [Zend incompatibility](https://github.com/facebook/hiphop-php/issues?labels=zend+incompatibility&page=1&state=open) are real issues reported by the community in existing PHP code and [frameworks](https://github.com/facebook/hiphop-php/wiki/OSS-PHP-Frameworks-Unit-Testing:-General) that could use some attention.
## Submitting Pull Requests
Before changes can be accepted a [Contributor Licensing Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hiphop-php/raw/master/hphp/doc/FB_Individual_CLA.pdf) - print, sign, scan, link) must be signed.
Please add appropriate test cases as you make changes; see [here](hphp/test) for more information. Travis-CI is integrated with this GitHub project and will provide test results automatically on all pulls.
## Additional Resources
* IRC:[#hhvm on freenode](http://webchat.freenode.net/?channels=hhvm)
* [Issue tracker](http://github.com/facebook/hiphop-php/issues)
+16 -3
Ver Arquivo
@@ -4,6 +4,10 @@ HipHop VM (HHVM) is a new open-source virtual machine designed for executing pro
HipHop is most commonly run as a standalone server, replacing both Apache and modphp.
## FAQ
Our [FAQ](https://github.com/facebook/hiphop-php/wiki/FAQ) has answers to many common questions about HHVM, from [general questions](https://github.com/facebook/hiphop-php/wiki/FAQ#general) to questions geared towards those that want to [use](https://github.com/facebook/hiphop-php/wiki/FAQ#users) or [contribute](https://github.com/facebook/hiphop-php/wiki/FAQ#contributors) to HHVM.
## Installing
You can install a [prebuilt package](https://github.com/facebook/hiphop-php/wiki#installing-pre-built-packages-for-hhvm) or [compile from source](https://github.com/facebook/hiphop-php/wiki#building-hhvm).
@@ -22,12 +26,21 @@ For anything more complicated, you'll want to make a [config.hdf](https://github
## Contributing
We'd love to have your help in making HipHop better. If you run into problems, please open an [issue](http://github.com/facebook/hiphop-php/issues), or better yet, fork us and send a pull request. Join us on [#hhvm on freenode](http://webchat.freenode.net/?channels=hhvm).
We'd love to have your help in making HipHop better.
Before changes can be accepted a [Contributor License Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hiphop-php/raw/master/hphp/doc/FB_Individual_CLA.pdf) - print, sign, scan, link) must be signed.
If you run into problems, please open an [issue](http://github.com/facebook/hiphop-php/issues), or better yet, [fork us and send a pull request](https://github.com/facebook/hiphop-php/pulls). Join us on [#hhvm on freenode](http://webchat.freenode.net/?channels=hhvm).
If you want to help but don't know where to start, try fixing some of the [Zend tests that don't pass](hphp/test/zend/bad). You can run them with [hphp/test/run](hphp/test/run). When they work, move them to [zend/good](hphp/test/zend/good) and send a pull request.
Before changes can be accepted a [Contributors Licensing Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hiphop-php/raw/master/hphp/doc/FB_Individual_CLA.pdf) - print, sign, scan, link) must be signed.
All the open issues tagged [Zend incompatibility](https://github.com/facebook/hiphop-php/issues?labels=zend+incompatibility&page=1&state=open) are real issues reported by the community in existing PHP code and [frameworks](https://github.com/facebook/hiphop-php/wiki/OSS-PHP-Frameworks-Unit-Testing:-General) that could use some attention. Please add appropriate test cases as you make changes; see [here](hphp/test) for more information. Travis-CI is integrated with this GitHub project and will provide test results automatically on all pulls.
## Licence
## License
HipHop VM is licensed under the PHP and Zend licenses except as otherwise noted.
## Reporting Crashes
See [Reporting Crashes](https://github.com/facebook/hiphop-php/wiki/Reporting-Crashes) for helpful tips on how to report crashes in an actionable manner.
+39 -6
Ver Arquivo
@@ -11,20 +11,56 @@ if [ "$0" != "$SCRIPT_NAME" ]; then
exit 1
fi
if [ "x${TRAVIS}" != "x" ]; then
# Collect some stats for use in tuning build later on
free
CPUS=`cat /proc/cpuinfo | grep -E '^processor' | tail -1 | cut -d : -f 2`
CPUS=`expr ${CPUS} + 1`
echo "CPUs: ${CPUS}"
fi
export CMAKE_PREFIX_PATH=`/bin/pwd`/..
export HPHP_HOME=`/bin/pwd`
sudo apt-get install git-core cmake g++ libboost1.48-dev libmysqlclient-dev \
# install apt-fast to speedup later dependency installation
sudo add-apt-repository -y ppa:apt-fast/stable
sudo apt-get update
sudo apt-get install apt-fast
# install the actual dependencies
sudo apt-fast -y update
sudo apt-fast -y install git-core cmake g++ libboost1.48-dev libmysqlclient-dev \
libxml2-dev libmcrypt-dev libicu-dev openssl build-essential binutils-dev \
libcap-dev libgd2-xpm-dev zlib1g-dev libtbb-dev libonig-dev libpcre3-dev \
autoconf libtool libcurl4-openssl-dev libboost-regex1.48-dev libboost-system1.48-dev \
libboost-program-options1.48-dev libboost-filesystem1.48-dev wget memcached \
libreadline-dev libncurses-dev libmemcached-dev libbz2-dev \
libc-client2007e-dev php5-mcrypt php5-imagick libgoogle-perftools-dev \
libcloog-ppl0 libelf-dev libdwarf-dev libunwind7-dev subversion
libcloog-ppl0 libelf-dev libdwarf-dev libunwind7-dev subversion &
git clone git://github.com/libevent/libevent.git --quiet &
git clone git://github.com/bagder/curl.git --quiet &
svn checkout http://google-glog.googlecode.com/svn/trunk/ google-glog --quiet &
wget http://www.canonware.com/download/jemalloc/jemalloc-3.0.0.tar.bz2 --quiet &
# wait until all background processes finished
FAIL=0
for job in `jobs -p`
do
echo "waiting for background job $job"
wait $job || let "FAIL+=1"
done
if [ "$FAIL" == "0" ];
then
echo "all downloads finished"
else
echo "$FAIL errors while downloading!"
exit 100
fi
# libevent
git clone git://github.com/libevent/libevent.git
cd libevent
git checkout release-1.4.14b-stable
cat ../hphp/third_party/libevent-1.4.14.fb-changes.diff | patch -p1
@@ -35,7 +71,6 @@ make install
cd ..
# curl
git clone git://github.com/bagder/curl.git
cd curl
./buildconf
./configure --prefix=$CMAKE_PREFIX_PATH
@@ -44,7 +79,6 @@ make install
cd ..
# glog
svn checkout http://google-glog.googlecode.com/svn/trunk/ google-glog
cd google-glog
./configure --prefix=$CMAKE_PREFIX_PATH
make
@@ -52,7 +86,6 @@ make install
cd ..
# jemaloc
wget http://www.canonware.com/download/jemalloc/jemalloc-3.0.0.tar.bz2
tar xjvf jemalloc-3.0.0.tar.bz2
cd jemalloc-3.0.0
./configure --prefix=$CMAKE_PREFIX_PATH
+14 -21
Ver Arquivo
@@ -22,9 +22,8 @@ SET(USE_HHVM TRUE)
SET(ENV{HHVM} 1)
ADD_DEFINITIONS("-DHHVM -DHHVM_BINARY=1 -DHHVM_PATH=\\\"${HPHP_HOME}/hphp/hhvm/hhvm\\\"")
set(RECURSIVE_SOURCE_SUBDIRS runtime/base runtime/debugger runtime/eval runtime/ext runtime/vm util)
set(RECURSIVE_SOURCE_SUBDIRS runtime/base runtime/debugger runtime/eval runtime/ext runtime/server runtime/vm)
foreach (dir ${RECURSIVE_SOURCE_SUBDIRS})
auto_sources(files "*.cpp" "RECURSE" "${CMAKE_CURRENT_SOURCE_DIR}/${dir}")
list(APPEND CXX_SOURCES ${files})
@@ -40,6 +39,9 @@ if(NOT LINUX)
list(REMOVE_ITEM CXX_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/runtime/vm/debug/elfwriter.cpp)
endif()
# Not working with off-the-shelf libevent
list(REMOVE_ITEM CXX_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/runtime/server/server-name-indication.cpp")
# remove ext_hhvm, and anything in a test folder
foreach (file ${CXX_SOURCES})
if (${file} MATCHES "ext_hhvm")
@@ -61,26 +63,7 @@ add_subdirectory(third_party/lz4)
add_subdirectory(third_party/double-conversion)
add_subdirectory(third_party/folly)
foreach (CXX_FILE ${CXX_SOURCES})
if(${CXX_FILE} MATCHES ".no.cpp$")
SET_SOURCE_FILES_PROPERTIES(
${CXX_FILE}
PROPERTIES
COMPILE_FLAGS -O0
)
endif()
endforeach()
add_custom_command(
OUTPUT hphp_repo_schema.h hphp_build_info.cpp
COMMAND hphp/util/generate_buildinfo.sh
DEPENDS ${CXX_SOURCES} ${C_SOURCES}
WORKING_DIRECTORY ${HPHP_HOME}
COMMENT "Generating Repo Schema ID and Compiler ID"
VERBATIM)
ADD_LIBRARY(hphp_runtime_static STATIC
hphp_repo_schema.h hphp_build_info.cpp
${CXX_SOURCES} ${C_SOURCES} ${ASM_SOURCES})
SET_TARGET_PROPERTIES(hphp_runtime_static PROPERTIES OUTPUT_NAME "hphp_runtime")
SET_TARGET_PROPERTIES(hphp_runtime_static PROPERTIES PREFIX "lib")
@@ -89,9 +72,16 @@ SET_TARGET_PROPERTIES(hphp_runtime_static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
SET(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> q <TARGET> <LINK_FLAGS> <OBJECTS>")
hphp_link(hphp_runtime_static)
add_dependencies(hphp_runtime_static hphp_parser)
add_subdirectory("tools/bootstrap")
add_subdirectory(vixl)
add_subdirectory(neo)
add_subdirectory(parser)
add_subdirectory(zend)
add_subdirectory(util)
add_subdirectory(compiler)
add_subdirectory(runtime/ext_hhvm)
add_subdirectory(hhvm)
@@ -100,3 +90,6 @@ add_subdirectory(system)
if (NOT "$ENV{HPHP_NOTEST}" STREQUAL "1")
add_subdirectory(test)
endif ()
# Keep this last
add_subdirectory(tools/hphpize)
+117
Ver Arquivo
@@ -0,0 +1,117 @@
Next release
- <cool stuff goes here>
"Sausage" 14-Oct-2013
- Fixed issue that caused memory_get_usage to report double the actual usage.
- Direct invocation of callable arrays: $f = [$cls_or_instance, 'method']; $f()
- ASAN clean
- Support dynamically loadable extensions
- Support loading mini-systemlibs from extensions
"Tabasco" 30-Sep-2013
- Fix issues with __toString() functions that return non-string values
- Don't allow mock classes to extend collection classes
- Smarter memory allocation and scheduling for NUMA systems
- Improve profiler performance in the jit
- Fix several Zend compatibility issues
- Fix several bugs uncovered by ASAN
- Add collection support to array_keys, array_values, and array_combine
- Return a set-like array from Set::toArray
- Add to(Vector|Map|StableMap|Set) methods to collections
- Collections convert to boolean false when empty
- get_class_vars invokes the autoloader when necessary
- Rework the Zend compatibility layer to be more robust
- Allow traits to implement interfaces
- Support arbitrary expressions inside empty()
"Bobotie" 16-Sep-2013
- HNI (HipHop Native Interface) for calling C++ functions from Php
- Fix PropertyAccessorMap::isset
- Expose more POSIX constants
- Fixed behavior of stream_get_contents when default args are used.
- Implement str_getcsv, and fix some fgetcsv related issues.
- [IPv6] Fix stream_socket_recvfrom & stream_socket_sendto.
- [IPv6] Fix socket_sentto_recvfrom_ipv6_udp Zend compatibility.
- Optimize closure invocation and __invoke (~3x faster to invoke)
- Import gettext extension
- string and object allocation optimizations (reduced memory usage for both)
- Import YAML extension
- Import ftp extension
"Kimchi" 2-Sep-2013
- Fix order of custom attributes and visibility in ctor arg promotion
- Implement CachingIterator
- Implement RecursiveCachingIterator
- Generalized heuristic for choosing when to inline in the jit
- Introduced a Zend compatibility layer to compile extensions
- Imported calendar extension
- Use gcc-4.8.1 by default
- Improve hhvm commandline parsing logic
- Fix register_shutdown in session_set_save_handler to match PHP 5.4
- Add "native" functions for use in Systemlib
- PHP extension source-compatitblility layer
- Fix ArrayIterator constructor PHP compatibility
- Enable building against libmemcached 1.0.8
- Debugger: $_ not cleared but still printed after exception
- Fix clone of SplPriorityQueue
- Debugger: Fix bugs when multiple threads hit the same breakpoint
- Fix several namespace bugs
- Several PHP compatibility fixes for ArrayObject and ArrayIterator
- Fix list assignment with collection literals
- support "tuple(...)" in initializer expressions
- HHVM should compile with libmemcached 1.0.9+
- Support "(new Vector {..})->method()" style syntax
- use trigger_error in PHP for Redis user errors
- multiple simplexml fixes
- fixed serialize/unserialize for SplObjectStorage
- Implement ReflectionParameter::IsCallable()
"Achiote" 19-Aug-2013
- Async stack traces in the debugger via the "wa" command
- Fix late static binding in static closures
- Fix breakpoints on generators
- Add SplObserver and SplSubject interfaces
- Update Iterable interface and add toArray() method
- Allow __get for undefined properties
- Implement get_included_files()
- Limit use of huge pages
"Churrasco" 05-Aug-2013
- Implement stream_is_local
- Implement read support for .phar
- Implement assert with string arguments
- Implement RecursiveArrayIterator
- Implement php_strip_whitespace()
- Support for timeouts in cli mode
- Closure allocation optimizations (~2x faster to allocate a closure)
- Implement Redis session handler
- New memory profiler, hhprof, with pprof compatible output
- Update isset($string[$k]) and empty($string[$k) to PHP 5.5 semantics
- Fixed a few parser bugs
- Fixed a few bugs with token_get_all()
- Fix (string)$obj semantics when __toString() is not defined
"Tamale" 22-Jul-2013
- Optimize vector-shaped Arrays (arrays with keys in range 0..size-1)
- Enable HHBC by default in debug builds
- Implement SplObjectStorage::getInfo()
- Initial rough draft of xhpast2, a replacement for xhpast
- fix compilation on Ubuntu 13.04
- OSX changes, next round
- Modify PHP's ext/standard/math/tests/(pow|abs).phpt to be HHVM friendly
- add XHP comment syntax based on http://www.w3.org/TR/REC-xml/#sec-comments
"Wasabi Peas" 08-Jul-2013
- always_assert when we run out of TC space
- Initial changes to get HHVM compiling on OSX
- Consolodate ObjectData and Instance
- Prototype heap tracing framework & Heap profiler
- Better JIT code generation for Mod and Div
- Fixes to enable compilation with clang
- Support for yield k => v
- Make HHVM's command line parsing closer to PHP
- Implement Redis extension
- Implement LimitIterator from SPL
- add SessionHandler from PHP 5.4
- Numerous Debugger fixes and new developer docs for Debugger
- Ported many extension tests to PHP
+1
Ver Arquivo
@@ -49,3 +49,4 @@ add_definitions(-DALWAYS_ASSERT=1)
ADD_LIBRARY(hphp_analysis STATIC ${CXX_SOURCES} ${C_SOURCES})
target_link_libraries(hphp_analysis ${Boost_LIBRARIES})
add_dependencies(hphp_analysis hphp_parser)
+26 -33
Ver Arquivo
@@ -36,6 +36,8 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/include_expression.h"
#include "hphp/compiler/expression/closure_expression.h"
#include "hphp/compiler/expression/yield_expression.h"
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/statement/catch_statement.h"
@@ -64,14 +66,14 @@
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/util/parser/location.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/parser/location.h"
#include "hphp/util/util.h"
#define spc(T,p) boost::static_pointer_cast<T>(p)
#define dpc(T,p) boost::dynamic_pointer_cast<T>(p)
#define spc(T,p) static_pointer_cast<T>(p)
#define dpc(T,p) dynamic_pointer_cast<T>(p)
using namespace HPHP;
using std::string;
@@ -746,15 +748,6 @@ void AliasManager::killLocals() {
goto kill_it;
case Expression::KindOfBinaryOpExpression:
if (!(effects & emask) &&
getOpForAssignmentOp(spc(BinaryOpExpression, e)->getOp())) {
if (okToKill(spc(BinaryOpExpression, e)->getExp1(), false)) {
e->setContext(Expression::DeadStore);
m_replaced++;
++it;
continue;
}
}
cleanInterf(spc(BinaryOpExpression, e)->getExp1(), ++it, end, depth);
continue;
@@ -1526,8 +1519,7 @@ ExpressionPtr AliasManager::canonicalizeNode(
e->is(Expression::KindOfSimpleVariable) &&
!e->isThis()) {
Symbol *s = spc(SimpleVariable, e)->getSymbol();
if (s && !s->isParameter() && !s->isGeneratorParameter() &&
!s->isClosureVar()) {
if (s && !s->isParameter() && !s->isClosureVar()) {
rep = e->makeConstant(m_arp, "null");
Compiler::Error(Compiler::UseUndeclaredVariable, e);
if (m_variables->getAttribute(VariableTable::ContainsCompact)) {
@@ -1587,6 +1579,7 @@ ExpressionPtr AliasManager::canonicalizeNode(
cur = next;
}
if (!m_inCall &&
!last->is(Expression::KindOfAwaitExpression) &&
!last->is(Expression::KindOfYieldExpression) &&
ae->isUnused() && m_accessList.isLast(ae) &&
!e->hasAnyContext(Expression::AccessContext |
@@ -2115,6 +2108,7 @@ int AliasManager::collectAliasInfoRecur(ConstructPtr cs, bool unused) {
}
cs->clearVisited();
cs->clearChildOfYield();
StatementPtr s = dpc(Statement, cs);
if (s) {
@@ -2405,6 +2399,9 @@ int AliasManager::collectAliasInfoRecur(ConstructPtr cs, bool unused) {
// expressions. TODO: revisit this later
m_inlineAsExpr = false;
break;
case Expression::KindOfYieldExpression:
spc(YieldExpression, e)->getValueExpression()->setChildOfYield();
break;
case Expression::KindOfUnaryOpExpression:
if (Option::EnableEval > Option::NoEval && spc(UnaryOpExpression, e)->
getOp() == T_EVAL) {
@@ -2640,8 +2637,11 @@ private:
if (sv && se) {
const string &s = se->getLiteralString();
if (s.empty()) return ExpressionPtr();
if (interface_supports_array(s)) {
// This could be an array, so don't assert anything
if (interface_supports_array(s) ||
interface_supports_string(s) ||
interface_supports_int(s) ||
interface_supports_double(s)) {
// This could be a primitive type, so don't assert anything
return ExpressionPtr();
}
TypePtr o(Type::CreateObjectType(Util::toLower(s)));
@@ -3327,19 +3327,12 @@ public:
DataFlowWalker::walk(*this);
ControlBlock *b = m_graph.getDfBlock(1);
std::map<std::string,int>::iterator it = m_gidMap.find("v:this");
if (m->getOrigGeneratorFunc()) {
BitOps::set(m_gidMap.size(), b->getRow(DataFlow::PRefIn),
BitOps::Bits(-1));
BitOps::set(m_gidMap.size(), b->getRow(DataFlow::PInitIn),
BitOps::Bits(-1));
} else {
if (it != m_gidMap.end() && it->second) {
b->setBit(DataFlow::PRefIn, it->second);
b->setBit(DataFlow::PInitIn, it->second);
}
updateParamInfo(m->getParams(), Option::HardTypeHints);
updateParamInfo(m->getFunctionScope()->getClosureVars(), false);
if (it != m_gidMap.end() && it->second) {
b->setBit(DataFlow::PRefIn, it->second);
b->setBit(DataFlow::PInitIn, it->second);
}
updateParamInfo(m->getParams(), Option::HardTypeHints);
updateParamInfo(m->getFunctionScope()->getClosureVars(), false);
}
void updateParamInfo(ExpressionListPtr el, bool useDefaults) {
@@ -3590,8 +3583,8 @@ public:
} else {
auto sym = vars->getSymbol(l);
auto dt = vars->getFinalType(l)->getDataType();
if (!sym->isStatic()
&& !IS_REFCOUNTED_TYPE(dt) && dt != KindOfUnknown) {
if (!sym->isStatic() && dt != KindOfUnknown &&
!IS_REFCOUNTED_TYPE(dt)) {
rs->addNonRefcounted(l);
}
}
@@ -3613,7 +3606,7 @@ public:
bool walk() { ControlFlowGraphWalker::walk(*this); return m_changed; }
int afterEach(ConstructRawPtr p, int i, ConstructPtr kid) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(kid)) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(kid)) {
if (e->isTypeAssertion()) return WalkContinue; // nothing to do
bool safeForProp =
+24 -21
Ver Arquivo
@@ -46,14 +46,14 @@
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/runtime/ext/ext_json.h"
#include "hphp/runtime/base/zend/zend_printf.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/util/atomic.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/util/process.h"
#include "hphp/util/job_queue.h"
#include "hphp/util/job-queue.h"
#include "hphp/util/timer.h"
using namespace HPHP;
@@ -456,8 +456,10 @@ void AnalysisResult::markRedeclaringClasses() {
* as redeclaring for now.
*/
for (auto& kv : m_classAliases) {
markRedeclaring(Util::toLower(kv.first));
markRedeclaring(Util::toLower(kv.second));
assert(kv.first == Util::toLower(kv.first));
assert(kv.second == Util::toLower(kv.second));
markRedeclaring(kv.first);
markRedeclaring(kv.second);
}
/*
@@ -467,7 +469,8 @@ void AnalysisResult::markRedeclaringClasses() {
* that things like 'instanceof Foo' will not mean the same thing.
*/
for (auto& name : m_typeAliasNames) {
markRedeclaring(Util::toLower(name));
assert(Util::toLower(name) == name);
markRedeclaring(name);
}
}
@@ -980,7 +983,7 @@ public:
virtual void doJob(BlockScope *scope) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumDoJobCalls);
++AnalysisResult::s_NumDoJobCalls;
ConcurrentBlockScopeRawPtrIntHashMap::accessor acc;
AnalysisResult::s_DoJobUniqueScopes.insert(acc,
BlockScopeRawPtr(scope));
@@ -1040,13 +1043,13 @@ public:
break;
case BlockScope::MarkProcessing:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumForceRerunGlobal);
++AnalysisResult::s_NumForceRerunGlobal;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
pf->first->setForceRerun(true);
break;
case BlockScope::MarkProcessed:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateGlobal);
++AnalysisResult::s_NumReactivateGlobal;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
if (visitor->activateScope(pf->first)) {
visitor->enqueue(pf->first);
@@ -1082,7 +1085,7 @@ public:
int m = pf->first->getMark();
if (pf->second & useKinds && m == BlockScope::MarkProcessed) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateUseKinds);
++AnalysisResult::s_NumReactivateUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
bool ready = visitor->activateScope(pf->first);
always_assert(!ready);
@@ -1106,7 +1109,7 @@ public:
// in its entirety. Thus, we must force it to run again in
// order to be able to observe all the updates.
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumForceRerunUseKinds);
++AnalysisResult::s_NumForceRerunUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
always_assert(pf->first->getNumDepsToWaitFor() == 0);
pf->first->setForceRerun(true);
@@ -1237,11 +1240,11 @@ AnalysisResult::postWaitCallback(bool first,
}
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
int AnalysisResult::s_NumDoJobCalls = 0;
int AnalysisResult::s_NumForceRerunGlobal = 0;
int AnalysisResult::s_NumReactivateGlobal = 0;
int AnalysisResult::s_NumForceRerunUseKinds = 0;
int AnalysisResult::s_NumReactivateUseKinds = 0;
std::atomic<int> AnalysisResult::s_NumDoJobCalls(0);
std::atomic<int> AnalysisResult::s_NumForceRerunGlobal(0);
std::atomic<int> AnalysisResult::s_NumReactivateGlobal(0);
std::atomic<int> AnalysisResult::s_NumForceRerunUseKinds(0);
std::atomic<int> AnalysisResult::s_NumReactivateUseKinds(0);
ConcurrentBlockScopeRawPtrIntHashMap
AnalysisResult::s_DoJobUniqueScopes;
@@ -1516,7 +1519,7 @@ DepthFirstVisitor<InferTypes, OptVisitor>::visitScope(BlockScopeRawPtr scope) {
// there are potentially AST nodes which are interested in the updated
// return type
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumForceRerunSelfCaller);
++RescheduleException::s_NumForceRerunSelfCaller;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
scope->setForceRerun(true);
}
@@ -1533,7 +1536,7 @@ DepthFirstVisitor<InferTypes, OptVisitor>::visitScope(BlockScopeRawPtr scope) {
// potential deadlock detected- reschedule
// this scope to run at a later time
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumReschedules);
++RescheduleException::s_NumReschedules;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
ret |= scope->getUpdated();
if (m) {
@@ -1590,9 +1593,9 @@ bool AnalysisResult::postWaitCallback<InferTypes>(
}
#ifdef HPHP_INSTRUMENT_TYPE_INF
int RescheduleException::s_NumReschedules = 0;
int RescheduleException::s_NumForceRerunSelfCaller = 0;
int RescheduleException::s_NumRetTypesChanged = 0;
std::atomic<int> RescheduleException::s_NumReschedules(0);
std::atomic<int> RescheduleException::s_NumForceRerunSelfCaller(0);
std::atomic<int> RescheduleException::s_NumRetTypesChanged(0);
LProfileMap BaseTryLock::s_LockProfileMap;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
+21 -13
Ver Arquivo
@@ -25,11 +25,11 @@
#include "hphp/compiler/analysis/function_container.h"
#include "hphp/compiler/package.h"
#include "hphp/util/string_bag.h"
#include "hphp/util/thread_local.h"
#include "hphp/util/string-bag.h"
#include "hphp/util/thread-local.h"
#include <boost/graph/adjacency_list.hpp>
#include "tbb/concurrent_hash_map.h"
#include <tbb/concurrent_hash_map.h>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -238,6 +238,14 @@ public:
ClassScopePtr findClass(const std::string &className,
FindClassBy by);
/*
* Returns: whether the given name is the name of any type aliases
* in the whole program.
*/
bool isTypeAliasName(const std::string& name) const {
return m_typeAliasNames.count(name);
}
/**
* Find all the redeclared classes by the name, excluding system classes.
* Note that system classes cannot be redeclared.
@@ -335,12 +343,12 @@ private:
std::string m_outputPath;
public:
AnalysisResultPtr shared_from_this() {
return boost::static_pointer_cast<AnalysisResult>
return static_pointer_cast<AnalysisResult>
(BlockScope::shared_from_this());
}
AnalysisResultConstPtr shared_from_this() const {
return boost::static_pointer_cast<const AnalysisResult>
return static_pointer_cast<const AnalysisResult>
(BlockScope::shared_from_this());
}
@@ -396,12 +404,12 @@ public:
s_changedScopesMapThreadLocal);
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
static int s_NumDoJobCalls;
static std::atomic<int> s_NumDoJobCalls;
static ConcurrentBlockScopeRawPtrIntHashMap s_DoJobUniqueScopes;
static int s_NumForceRerunGlobal;
static int s_NumReactivateGlobal;
static int s_NumForceRerunUseKinds;
static int s_NumReactivateUseKinds;
static std::atomic<int> s_NumForceRerunGlobal;
static std::atomic<int> s_NumReactivateGlobal;
static std::atomic<int> s_NumForceRerunUseKinds;
static std::atomic<int> s_NumReactivateUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
private:
@@ -429,9 +437,9 @@ public:
Exception(), m_scope(scope) {}
BlockScopeRawPtr &getScope() { return m_scope; }
#ifdef HPHP_INSTRUMENT_TYPE_INF
static int s_NumReschedules;
static int s_NumForceRerunSelfCaller;
static int s_NumRetTypesChanged;
static std::atomic<int> s_NumReschedules;
static std::atomic<int> s_NumForceRerunSelfCaller;
static std::atomic<int> s_NumRetTypesChanged;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
private:
BlockScopeRawPtr m_scope;
+3 -3
Ver Arquivo
@@ -23,17 +23,17 @@ using namespace HPHP;
bool FunctionWalker::SkipRecurse(ConstructPtr cp) {
StatementPtr s(
boost::dynamic_pointer_cast<Statement>(cp));
dynamic_pointer_cast<Statement>(cp));
return SkipRecurse(s);
}
bool FunctionWalker::SkipRecurse(ConstructConstPtr cp) {
StatementConstPtr s(
boost::dynamic_pointer_cast<const Statement>(cp));
dynamic_pointer_cast<const Statement>(cp));
return SkipRecurse(s);
}
bool FunctionWalker::SkipRecurse(ConstructRawPtr cp) {
StatementRawPtr s(
boost::dynamic_pointer_cast<Statement>(cp));
dynamic_pointer_cast<Statement>(cp));
return SkipRecurse(s);
}
+3 -2
Ver Arquivo
@@ -14,10 +14,11 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/analysis/block_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/constant_table.h"
@@ -94,7 +95,7 @@ FunctionScopeRawPtr BlockScope::getContainingNonClosureFunction() {
// walk out through all the closures
while (bs && bs->is(BlockScope::FunctionScope)) {
HPHP::FunctionScope *fs = static_cast<HPHP::FunctionScope*>(bs);
if (!fs->isClosure() && !fs->isGeneratorFromClosure()) {
if (!fs->isClosure()) {
return FunctionScopeRawPtr(fs);
}
bs = bs->m_outerScope.get();
+2 -2
Ver Arquivo
@@ -23,7 +23,7 @@
#include "hphp/util/lock.h"
#include "hphp/runtime/base/macros.h"
#include "tbb/concurrent_hash_map.h"
#include <tbb/concurrent_hash_map.h>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -66,7 +66,7 @@ typedef SimpleMutex InferTypesMutex;
* Base class of ClassScope and FunctionScope.
*/
class BlockScope : private boost::noncopyable,
public boost::enable_shared_from_this<BlockScope> {
public std::enable_shared_from_this<BlockScope> {
public:
enum KindOf {
ClassScope,
+9 -112
Ver Arquivo
@@ -34,14 +34,14 @@
#include "hphp/compiler/statement/function_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/compiler/statement/class_variable.h"
#include "hphp/compiler/statement/class_constant.h"
#include "hphp/compiler/statement/use_trait_statement.h"
#include "hphp/compiler/statement/trait_prec_statement.h"
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/util/util.h"
#include <boost/foreach.hpp>
@@ -62,7 +62,7 @@ ClassScope::ClassScope(KindOf kindOf, const std::string &name,
m_kindOf(kindOf), m_derivesFromRedeclaring(FromNormal),
m_traitStatus(NOT_FLATTENED), m_volatile(false),
m_persistent(false), m_derivedByDynamic(false),
m_sep(false), m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) {
m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) {
m_dynamic = Option::IsDynamicClass(m_name);
@@ -92,7 +92,7 @@ ClassScope::ClassScope(AnalysisResultPtr ar,
m_kindOf(KindOfObjectClass), m_derivesFromRedeclaring(FromNormal),
m_traitStatus(NOT_FLATTENED), m_dynamic(false),
m_volatile(false), m_persistent(false),
m_derivedByDynamic(false), m_sep(false), m_needsCppCtor(false),
m_derivedByDynamic(false), m_needsCppCtor(false),
m_needsInit(true), m_knownBases(0) {
BOOST_FOREACH(FunctionScopePtr f, methods) {
if (f->getName() == "__construct") setAttribute(HasConstructor);
@@ -403,23 +403,12 @@ MethodStatementPtr
ClassScope::importTraitMethod(const TraitMethod& traitMethod,
AnalysisResultPtr ar,
string methName,
GeneratorRenameMap& genRenameMap,
const std::map<string, MethodStatementPtr>&
importedTraitMethods) {
MethodStatementPtr meth = traitMethod.m_method;
string origMethName = traitMethod.m_originalName;
ModifierExpressionPtr modifiers = traitMethod.m_modifiers;
if (meth->getOrigGeneratorFunc()) {
const string &name = meth->getOrigGeneratorFunc()->getName();
if (!importedTraitMethods.count(name)) {
// Dont import the generator, if the origGenerator wasnt imported
// this happens when a generator in the trait is hidden by a non-generator
// method in the importing class.
return MethodStatementPtr();
}
}
MethodStatementPtr cloneMeth = dynamic_pointer_cast<MethodStatement>(
dynamic_pointer_cast<ClassStatement>(m_stmt)->addClone(meth));
cloneMeth->setName(methName);
@@ -434,17 +423,9 @@ ClassScope::importTraitMethod(const TraitMethod& traitMethod,
ClassScopePtr cScope = dynamic_pointer_cast<ClassScope>(shared_from_this());
cloneMeth->fixupSelfAndParentTypehints( cScope );
// Generator methods need to be renamed, otherwise code gen produces multiple
// continuation classes with the same name
if (funcScope->isGenerator()) {
const string& newName = getNewGeneratorName(funcScope, genRenameMap);
methName = origMethName = newName;
cloneMeth->setName(newName);
cloneMeth->setOriginalName(newName);
}
FunctionScopePtr cloneFuncScope
(new HPHP::FunctionScope(funcScope, ar, methName, origMethName, cloneMeth,
cloneMeth->getModifiers()));
cloneMeth->getModifiers(), cScope->isUserClass()));
cloneMeth->resetScope(cloneFuncScope, true);
cloneFuncScope->setOuterScope(shared_from_this());
informClosuresAboutScopeClone(cloneMeth, cloneFuncScope, ar);
@@ -750,85 +731,6 @@ void ClassScope::removeSpareTraitAbstractMethods(AnalysisResultPtr ar) {
}
}
const string& ClassScope::getNewGeneratorName(
FunctionScopePtr genFuncScope, GeneratorRenameMap &genRenameMap) {
assert(genFuncScope->isGenerator());
const string& oldName = genFuncScope->getName();
GeneratorRenameMap::iterator mapIt = genRenameMap.find(oldName);
if (mapIt != genRenameMap.end()) {
return mapIt->second;
}
string newName = ParserBase::newContinuationName(
oldName + "_" + lexical_cast<string>(genFuncScope->getNewID())
);
genRenameMap[oldName] = newName;
return genRenameMap[oldName];
}
void
ClassScope::renameCreateContinuationCalls(AnalysisResultPtr ar,
ConstructPtr c,
ImportedMethodMap &importedMethods) {
if (!c) return;
SimpleFunctionCallPtr funcCall = dynamic_pointer_cast<SimpleFunctionCall>(c);
if (funcCall && funcCall->getName() == "hphp_create_continuation") {
ExpressionListPtr params = funcCall->getParams();
assert(params->getCount() >= 2);
const string &oldClassName =
dynamic_pointer_cast<ScalarExpression>((*params)[0])->getString();
ClassScopePtr oldClassScope = ar->findClass(oldClassName);
if (!oldClassScope || !oldClassScope->isTrait()) return;
const string &oldGenName =
dynamic_pointer_cast<ScalarExpression>((*params)[1])->getString();
MethodStatementPtr origGenStmt = importedMethods[Util::toLower(oldGenName)];
assert(origGenStmt);
const string &newGenName = origGenStmt->getOriginalName();
ExpressionPtr newGenExpr = funcCall->makeScalarExpression(ar, newGenName);
ExpressionPtr newClsExpr = funcCall->makeScalarExpression(ar, getName());
(*params)[0] = newClsExpr;
(*params)[1] = newGenExpr;
funcCall->analyzeProgram(ar);
return;
}
for (int i=0; i < c->getKidCount(); i++) {
renameCreateContinuationCalls(ar, c->getNthKid(i), importedMethods);
}
}
void ClassScope::relinkGeneratorMethods(
AnalysisResultPtr ar,
ImportedMethodMap &importedMethods) {
for (ImportedMethodMap::const_iterator methIt =
importedMethods.begin(); methIt != importedMethods.end(); methIt++) {
MethodStatementPtr newMeth = methIt->second;
// Skip non-generator methods
if (!newMeth) continue;
if (newMeth->getOrigGeneratorFunc()) {
// Get corresponding original generator method in the current class
const string& origGenName = newMeth->getOrigGeneratorFunc()->getName();
MethodStatementPtr origGenStmt = importedMethods[origGenName];
assert(origGenStmt);
// It must be an orig gen func already, we're just updating to point
// to the corresponding method cloned from the trait
assert(origGenStmt->getGeneratorFunc());
newMeth->setOrigGeneratorFunc(origGenStmt);
origGenStmt->setGeneratorFunc(newMeth);
}
// OrigGenerator methods need to have their hphp_create_continuation calls
// patched to the new generator name.
if (newMeth->getGeneratorFunc()) {
renameCreateContinuationCalls(ar, newMeth, importedMethods);
}
}
}
void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
if (m_traitStatus == FLATTENED) return;
if (m_traitStatus == BEING_FLATTENED) {
@@ -882,8 +784,6 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
std::map<string, MethodStatementPtr> importedTraitMethods;
std::vector<std::pair<string,const TraitMethod*> > importedTraitsWithOrigName;
GeneratorRenameMap genRenameMap;
// Actually import the methods
for (MethodToTraitListMap::const_iterator
iter = m_importMethToTraitMap.begin();
@@ -928,15 +828,12 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
const TraitMethod *traitMethod = importedTraitsWithOrigName[i].second;
MethodStatementPtr newMeth = importTraitMethod(
*traitMethod, ar, Util::toLower(traitMethod->m_originalName),
genRenameMap, importedTraitMethods);
importedTraitMethods);
if (newMeth) {
importedTraitMethods[sourceName] = newMeth;
}
}
// Relink generator and origGenerator methods
relinkGeneratorMethods(ar, importedTraitMethods);
// Import trait properties
importTraitProperties(ar);
@@ -1198,10 +1095,10 @@ void ClassScope::getAllParents(AnalysisResultConstPtr ar,
std::vector<std::string> &names) {
if (m_stmt) {
if (isInterface()) {
boost::dynamic_pointer_cast<InterfaceStatement>
dynamic_pointer_cast<InterfaceStatement>
(m_stmt)->getAllParents(ar, names);
} else {
boost::dynamic_pointer_cast<ClassStatement>
dynamic_pointer_cast<ClassStatement>
(m_stmt)->getAllParents(ar, names);
}
} else {
+1 -17
Ver Arquivo
@@ -25,7 +25,7 @@
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/util/json.h"
#include "hphp/util/case_insensitive.h"
#include "hphp/util/case-insensitive.h"
#include "hphp/compiler/option.h"
namespace HPHP {
@@ -169,10 +169,6 @@ public:
return m_derivedByDynamic;
}
/* Whether this class is brought in by a separable extension */
void setSepExtension() { m_sep = true;}
bool isSepExtension() const { return m_sep;}
/**
* Get/set attributes.
*/
@@ -407,7 +403,6 @@ private:
typedef std::list<TraitMethod> TraitMethodList;
typedef std::map<std::string, TraitMethodList> MethodToTraitListMap;
typedef std::map<std::string, std::string> GeneratorRenameMap;
MethodToTraitListMap m_importMethToTraitMap;
typedef std::map<std::string, MethodStatementPtr> ImportedMethodMap;
@@ -424,7 +419,6 @@ private:
unsigned m_volatile:1; // for class_exists
unsigned m_persistent:1;
unsigned m_derivedByDynamic:1;
unsigned m_sep:1;
unsigned m_needsCppCtor:1;
unsigned m_needsInit:1;
// m_knownBases has a bit for each base class saying whether
@@ -446,15 +440,11 @@ private:
MethodStatementPtr importTraitMethod(const TraitMethod& traitMethod,
AnalysisResultPtr ar,
std::string methName,
GeneratorRenameMap& genRenameMap,
const ImportedMethodMap &
importedTraitMethods);
void importTraitProperties(AnalysisResultPtr ar);
void relinkGeneratorMethods(AnalysisResultPtr ar,
ImportedMethodMap& importedMethods);
void findTraitMethodsToImport(AnalysisResultPtr ar, ClassScopePtr trait);
MethodStatementPtr findTraitMethod(AnalysisResultPtr ar,
@@ -477,12 +467,6 @@ private:
bool hasMethod(const std::string &methodName) const;
const std::string& getNewGeneratorName(FunctionScopePtr genFuncScope,
GeneratorRenameMap& genRenameMap);
void renameCreateContinuationCalls(AnalysisResultPtr ar, ConstructPtr c,
ImportedMethodMap &importedMethods);
};
///////////////////////////////////////////////////////////////////////////////
+1 -1
Ver Arquivo
@@ -25,7 +25,7 @@
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
+4 -5
Ver Arquivo
@@ -64,8 +64,8 @@ typedef hphp_hash_map<ConstructRawPtr, ControlBlock*,
class ControlFlowBuilder : public FunctionWalker {
public:
ControlFlowBuilder(ControlFlowGraph *g, bool isGenerator) :
m_graph(g), m_pass(0), m_isGenerator(isGenerator), m_cur(0), m_head(0) {}
explicit ControlFlowBuilder(ControlFlowGraph *g) :
m_graph(g), m_pass(0), m_cur(0), m_head(0) {}
int before(ConstructRawPtr cp);
int after(ConstructRawPtr cp);
@@ -161,7 +161,6 @@ private:
ControlFlowGraph *m_graph;
AstWalkerStateVec m_state;
int m_pass;
bool m_isGenerator;
ControlBlock *m_cur;
ControlBlock *m_head;
@@ -417,7 +416,7 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
case Statement::KindOfReturnStatement: {
setEdge(s, AfterConstruct, root(), AfterConstruct);
if (!m_isGenerator) noFallThrough(s);
noFallThrough(s);
/*
* Since almost anything in php /might/ throw, we
* approximate, and add edges from the beginning and
@@ -868,7 +867,7 @@ ControlFlowGraph *ControlFlowGraph::buildControlFlow(MethodStatementPtr m) {
ControlFlowGraph *graph = new ControlFlowGraph;
graph->m_stmt = m;
ControlFlowBuilder cfb(graph, !!m->getOrigGeneratorFunc());
ControlFlowBuilder cfb(graph);
cfb.run(m->getStmts());
graph->m_nextDfn = 1;
depth_first_visit(*graph, cfb.head(),
+1
Ver Arquivo
@@ -43,4 +43,5 @@ CODE_ERROR_ENTRY(InvalidTraitStatement)
CODE_ERROR_ENTRY(RedeclaredTrait)
CODE_ERROR_ENTRY(InvalidInstantiation)
CODE_ERROR_ENTRY(InvalidYield)
CODE_ERROR_ENTRY(InvalidAwait)
CODE_ERROR_ENTRY(BadDefaultValueType)
+8 -8
Ver Arquivo
@@ -221,16 +221,16 @@ void DataFlow::ComputePartialDying(const ControlFlowGraph &g) {
// DataFlowWalker
int DataFlowWalker::after(ConstructRawPtr cp) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(cp)) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(cp)) {
switch (e->getKindOf()) {
case Expression::KindOfSimpleVariable:
if (!boost::static_pointer_cast<SimpleVariable>(
if (!static_pointer_cast<SimpleVariable>(
e)->getAlwaysStash()) {
return WalkContinue;
}
break;
case Expression::KindOfBinaryOpExpression:
if (boost::static_pointer_cast<BinaryOpExpression>(
if (static_pointer_cast<BinaryOpExpression>(
e)->isShortCircuitOperator()) {
break;
}
@@ -246,7 +246,7 @@ int DataFlowWalker::after(ConstructRawPtr cp) {
for (int i = 0, nk = e->getKidCount(); i < nk; i++) {
ExpressionPtr k = e->getNthExpr(i);
if (k && k->is(Expression::KindOfSimpleVariable) &&
!boost::static_pointer_cast<SimpleVariable>(
!static_pointer_cast<SimpleVariable>(
k)->getAlwaysStash()) {
process(k);
}
@@ -260,13 +260,13 @@ int DataFlowWalker::after(ConstructRawPtr cp) {
}
int DataFlowWalker::afterEach(ConstructRawPtr cur, int i, ConstructRawPtr kid) {
if (ExpressionRawPtr k = boost::dynamic_pointer_cast<Expression>(kid)) {
if (ExpressionRawPtr k = dynamic_pointer_cast<Expression>(kid)) {
if (k->is(Expression::KindOfSimpleVariable) &&
!boost::static_pointer_cast<SimpleVariable>(k)->getAlwaysStash()) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(cur)) {
!static_pointer_cast<SimpleVariable>(k)->getAlwaysStash()) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(cur)) {
switch (e->getKindOf()) {
case Expression::KindOfBinaryOpExpression:
if (!boost::static_pointer_cast<BinaryOpExpression>(
if (!static_pointer_cast<BinaryOpExpression>(
e)->isShortCircuitOperator()) {
return WalkContinue;
}
+3 -3
Ver Arquivo
@@ -64,12 +64,12 @@ public:
}
StatementPtr visitStmtRecur(StatementPtr stmt) {
BlockScopeRawPtr scope = boost::dynamic_pointer_cast<LoopStatement>(stmt) ?
BlockScopeRawPtr scope = dynamic_pointer_cast<LoopStatement>(stmt) ?
stmt->getScope() : BlockScopeRawPtr();
for (int i = 0, n = stmt->getKidCount(); i < n; i++) {
if (ConstructPtr kid = stmt->getNthKid(i)) {
if (StatementPtr s = boost::dynamic_pointer_cast<Statement>(kid)) {
if (StatementPtr s = dynamic_pointer_cast<Statement>(kid)) {
if (FunctionWalker::SkipRecurse(s)) continue;
if (scope) scope->incLoopNestedLevel();
if (StatementPtr rep = visitStmtRecur(s)) {
@@ -78,7 +78,7 @@ public:
}
if (scope) scope->decLoopNestedLevel();
} else {
ExpressionPtr e = boost::dynamic_pointer_cast<Expression>(kid);
ExpressionPtr e = dynamic_pointer_cast<Expression>(kid);
if (ExpressionPtr rep = visitExprRecur(e)) {
stmt->setNthKid(i, rep);
stmt->getScope()->addUpdates(BlockScope::UseKindCaller);
+2 -2
Ver Arquivo
@@ -39,11 +39,11 @@ void Dictionary::build(MethodStatementPtr m) {
void Dictionary::build(StatementPtr stmt) {
for (int i = 0, n = stmt->getKidCount(); i < n; i++) {
if (ConstructPtr kid = stmt->getNthKid(i)) {
if (StatementPtr s = boost::dynamic_pointer_cast<Statement>(kid)) {
if (StatementPtr s = dynamic_pointer_cast<Statement>(kid)) {
if (FunctionWalker::SkipRecurse(s)) continue;
build(s);
} else {
ExpressionPtr e = boost::dynamic_pointer_cast<Expression>(kid);
ExpressionPtr e = dynamic_pointer_cast<Expression>(kid);
build(e);
}
}
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+42 -11
Ver Arquivo
@@ -111,7 +111,7 @@ public:
#define SLA std::vector<StrOff>&
#define ILA std::vector<IterPair>&
#define IVA int32_t
#define HA int32_t
#define LA int32_t
#define IA int32_t
#define I64A int64_t
#define DA double
@@ -131,7 +131,7 @@ public:
#undef SLA
#undef ILA
#undef IVA
#undef HA
#undef LA
#undef IA
#undef I64A
#undef DA
@@ -374,12 +374,14 @@ public:
class IncludeTimeFatalException : public Exception {
public:
ConstructPtr m_node;
bool m_parseFatal;
IncludeTimeFatalException(ConstructPtr node, const char* fmt, ...)
: Exception(), m_node(node) {
: Exception(), m_node(node), m_parseFatal(false) {
va_list ap; va_start(ap, fmt); format(fmt, ap); va_end(ap);
}
virtual ~IncludeTimeFatalException() throw() {}
EXCEPTION_COMMON_IMPL(IncludeTimeFatalException);
void setParseFatal(bool b = true) { m_parseFatal = b; }
};
void pushIterScope(Id id, IterKind kind) {
@@ -513,9 +515,6 @@ private:
int defI;
};
private:
void emitFatal(Emitter& e, const char* message);
private:
static const size_t kMinStringSwitchCases = 8;
UnitEmitter& m_ue;
@@ -531,7 +530,8 @@ private:
std::deque<PostponedNonScalars> m_postponedCinits;
std::deque<PostponedClosureCtor> m_postponedClosureCtors;
PendingIterVec m_pendingIters;
hphp_hash_set<std::string> m_generatorEmitted;
hphp_hash_map<std::string,FuncEmitter*> m_generatorEmitted;
hphp_hash_set<std::string> m_nonTopGeneratorEmitted;
hphp_hash_set<std::string> m_topMethodEmitted;
SymbolicStack m_evalStack;
bool m_evalStackIsUnknown;
@@ -546,7 +546,7 @@ private:
std::deque<ExnHandlerRegion*> m_exnHandlers;
std::deque<FaultRegion*> m_faultRegions;
std::deque<FPIRegion*> m_fpiRegions;
std::vector<HphpArray*> m_staticArrays;
std::vector<Array> m_staticArrays;
std::set<std::string,stdltistr> m_hoistables;
LocationPtr m_tempLoc;
std::map<StringData*, Label, string_data_lt> m_gotoLabels;
@@ -599,6 +599,7 @@ public:
void emitResolveClsBase(Emitter& e, int pos);
void emitClsIfSPropBase(Emitter& e);
Id emitVisitAndSetUnnamedL(Emitter& e, ExpressionPtr exp);
Id emitSetUnnamedL(Emitter& e);
void emitPushAndFreeUnnamedL(Emitter& e, Id tempLocal, Offset start);
void emitContinuationSwitch(Emitter& e, int ncase);
DataType analyzeSwitch(SwitchStatementPtr s, SwitchState& state);
@@ -628,6 +629,32 @@ public:
void postponeSinit(InterfaceStatementPtr m, FuncEmitter* fe, NonScalarVec* v);
void postponeCinit(InterfaceStatementPtr m, FuncEmitter* fe, NonScalarVec* v);
void emitPostponedMeths();
void bindUserAttributes(MethodStatementPtr meth,
FuncEmitter *fe,
bool &allowOverride);
void bindNativeFunc(MethodStatementPtr meth, FuncEmitter *fe);
void emitMethodMetadata(MethodStatementPtr meth,
ClosureUseVarVec* useVars,
bool top);
void fillFuncEmitterParams(FuncEmitter* fe,
ExpressionListPtr params,
bool builtin = false);
void emitMethodPrologue(Emitter& e, MethodStatementPtr meth);
void emitMethod(MethodStatementPtr meth);
std::pair<FuncEmitter*,bool> createFuncEmitterForGeneratorBody(
MethodStatementPtr meth,
FuncEmitter* fe,
vector<FuncEmitter*>& top_fes);
void emitAsyncMethod(MethodStatementPtr meth);
void emitGeneratorCreate(MethodStatementPtr meth);
void emitGeneratorBody(MethodStatementPtr meth);
void emitConstMethodCallNoParams(Emitter& e, string name);
void emitCreateStaticWaitHandle(Emitter& e, std::string cls,
std::function<void()> emitParam);
void emitSetFuncGetArgs(Emitter& e);
void emitMethodDVInitializers(Emitter& e,
MethodStatementPtr& meth,
Label& topOfBody);
void emitPostponedCtors();
void emitPostponedPSinit(PostponedNonScalars& p, bool pinit);
void emitPostponedPinits();
@@ -653,12 +680,16 @@ public:
void emitBuiltinCallArg(Emitter& e, ExpressionPtr exp, int paramId,
bool byRef);
void emitBuiltinDefaultArg(Emitter& e, Variant& v, DataType t, int paramId);
PreClass::Hoistable emitClass(Emitter& e, ClassScopePtr cNode,
bool topLevel);
void emitClass(Emitter& e, ClassScopePtr cNode, bool topLevel);
void emitTypedef(Emitter& e, TypedefStatementPtr);
void emitForeachListAssignment(Emitter& e, ListAssignmentPtr la,
int vLocalId);
void emitForeach(Emitter& e, ForEachStatementPtr fe);
void emitRestoreErrorReporting(Emitter& e, Id oldLevelLoc);
void emitMakeUnitFatal(Emitter& e, const std::string& message);
void emitMakeUnitFatal(Emitter& e,
const char* msg,
FatalKind k = FatalKind::Runtime,
bool skipFrame = false);
void addFunclet(Thunklet* body, Label* entry);
void emitFunclets(Emitter& e);
+31 -17
Ver Arquivo
@@ -34,7 +34,7 @@
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/include_expression.h"
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
@@ -73,8 +73,7 @@ FunctionScopePtr FileScope::setTree(AnalysisResultConstPtr ar,
return createPseudoMain(ar);
}
void FileScope::cleanupForError(AnalysisResultConstPtr ar,
int line, const string &msg) {
void FileScope::cleanupForError(AnalysisResultConstPtr ar) {
for (StringToClassScopePtrVecMap::const_iterator iter = m_classes.begin();
iter != m_classes.end(); ++iter) {
BOOST_FOREACH(ClassScopePtr cls, iter->second) {
@@ -90,8 +89,16 @@ void FileScope::cleanupForError(AnalysisResultConstPtr ar,
StringToClassScopePtrVecMap().swap(m_classes);
m_pseudoMain.reset();
m_tree.reset();
}
template <class Meth>
void makeFatalMeth(FileScope& file,
AnalysisResultConstPtr ar,
const std::string& msg,
int line,
Meth meth) {
LocationPtr loc(new Location());
loc->file = m_fileName.c_str();
loc->file = file.getName().c_str();
loc->first(line, 0);
loc->last(line, 0);
BlockScopePtr scope;
@@ -100,16 +107,30 @@ void FileScope::cleanupForError(AnalysisResultConstPtr ar,
SimpleFunctionCallPtr e(
new SimpleFunctionCall(scope, loc, "throw_fatal", false, args,
ExpressionPtr()));
e->setThrowFatal();
meth(e);
ExpStatementPtr exp(new ExpStatement(scope, loc, e));
StatementListPtr stmts(new StatementList(scope, loc));
stmts->addElement(exp);
FunctionScopePtr fs = setTree(ar, stmts);
fs->setOuterScope(shared_from_this());
FunctionScopePtr fs = file.setTree(ar, stmts);
fs->setOuterScope(file.shared_from_this());
fs->getStmt()->resetScope(fs);
fs->getStmt()->setLocation(loc);
setOuterScope(const_cast<AnalysisResult*>(ar.get())->shared_from_this());
file.setOuterScope(const_cast<AnalysisResult*>(ar.get())->shared_from_this());
}
void FileScope::makeFatal(AnalysisResultConstPtr ar,
const std::string& msg,
int line) {
auto meth = [](SimpleFunctionCallPtr e) { e->setThrowFatal(); };
makeFatalMeth(*this, ar, msg, line, meth);
}
void FileScope::makeParseFatal(AnalysisResultConstPtr ar,
const std::string& msg,
int line) {
auto meth = [](SimpleFunctionCallPtr e) { e->setThrowParseFatal(); };
makeFatalMeth(*this, ar, msg, line, meth);
}
bool FileScope::addFunction(AnalysisResultConstPtr ar,
@@ -193,13 +214,6 @@ int FileScope::getGlobalAttribute() const {
return m_attributes.back();
}
bool FileScope::needPseudoMainVariables() const {
VariableTablePtr variables = m_pseudoMain->getVariables();
return
variables->getAttribute(VariableTable::ContainsDynamicVariable) ||
variables->getSymbols().size() > 0;
}
///////////////////////////////////////////////////////////////////////////////
ExpressionPtr FileScope::getEffectiveImpl(AnalysisResultConstPtr ar) const {
@@ -399,8 +413,8 @@ FunctionScopePtr FileScope::createPseudoMain(AnalysisResultConstPtr ar) {
(new FunctionStatement(BlockScopePtr(), LocationPtr(),
ModifierExpressionPtr(),
false, pseudoMainName(),
ExpressionListPtr(), "", st, 0, "",
ExpressionListPtr()));
ExpressionListPtr(), TypeAnnotationPtr(),
st, 0, "", ExpressionListPtr()));
f->setFileLevel();
FunctionScopePtr pseudoMain(
new HPHP::FunctionScope(ar, true,
+10 -15
Ver Arquivo
@@ -25,7 +25,7 @@
#include "hphp/compiler/code_generator.h"
#include <boost/graph/adjacency_list.hpp>
#include "hphp/util/json.h"
#include "hphp/runtime/base/md5.h"
#include "hphp/util/md5.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -107,8 +107,11 @@ public:
* are the only functions a parser calls upon analysis results.
*/
FunctionScopePtr setTree(AnalysisResultConstPtr ar, StatementListPtr tree);
void cleanupForError(AnalysisResultConstPtr ar,
int line, const std::string &msg);
void cleanupForError(AnalysisResultConstPtr ar);
void makeFatal(AnalysisResultConstPtr ar,
const std::string& msg, int line);
void makeParseFatal(AnalysisResultConstPtr ar,
const std::string& msg, int line);
bool addFunction(AnalysisResultConstPtr ar, FunctionScopePtr funcScope);
bool addClass(AnalysisResultConstPtr ar, ClassScopePtr classScope);
@@ -138,7 +141,8 @@ public:
const std::string &decname);
void addClassAlias(const std::string& target, const std::string& alias) {
m_classAliasMap.insert(std::make_pair(target, alias));
m_classAliasMap.insert(std::make_pair(Util::toLower(target),
Util::toLower(alias)));
}
std::multimap<std::string,std::string> const& getClassAliases() const {
@@ -146,7 +150,7 @@ public:
}
void addTypeAliasName(const std::string& name) {
m_typeAliasNames.insert(name);
m_typeAliasNames.insert(Util::toLower(name));
}
std::set<std::string> const& getTypeAliasNames() const {
@@ -180,22 +184,14 @@ public:
const std::string &pseudoMainName();
void outputFileCPP(AnalysisResultPtr ar, CodeGenerator &cg);
bool load();
bool needPseudoMainVariables() const;
std::string outputFilebase() const;
void addPseudoMainVariable(const std::string &name) {
m_pseudoMainVariables.insert(name);
}
std::set<std::string> &getPseudoMainVariables() {
return m_pseudoMainVariables;
}
FunctionScopeRawPtr getPseudoMain() const {
return m_pseudoMain;
}
FileScopePtr shared_from_this() {
return boost::static_pointer_cast<FileScope>
return static_pointer_cast<FileScope>
(BlockScope::shared_from_this());
}
@@ -217,7 +213,6 @@ private:
vertex_descriptor m_vertex;
std::string m_pseudoMainName;
std::set<std::string> m_pseudoMainVariables;
BlockScopeSet m_providedDefs;
std::set<std::string> m_redecBases;
+57 -73
Ver Arquivo
@@ -33,12 +33,12 @@
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/util/atomic.h"
#include "hphp/util/util.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/variable_serializer.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/runtime/base/zend-string.h"
using namespace HPHP;
@@ -58,15 +58,17 @@ FunctionScope::FunctionScope(AnalysisResultConstPtr ar, bool method,
m_method(method), m_refReturn(reference), m_virtual(false),
m_hasOverride(false), m_perfectVirtual(false), m_overriding(false),
m_volatile(false), m_persistent(false), m_pseudoMain(inPseudoMain),
m_magicMethod(false), m_system(false), m_inlineable(false), m_sep(false),
m_magicMethod(false), m_system(false), m_inlineable(false),
m_containsThis(false), m_containsBareThis(0), m_nrvoFix(true),
m_inlineAsExpr(false), m_inlineSameContext(false),
m_contextSensitive(false),
m_directInvoke(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_generator(false),
m_async(false),
m_noLSB(false), m_nextLSB(false),
m_hasTry(false), m_hasGoto(false), m_localRedeclaring(false),
m_redeclaring(-1), m_inlineIndex(0), m_optFunction(0), m_nextID(0),
m_yieldLabelCount(0) {
m_yieldLabelCount(0), m_yieldLabelGen(-1) {
init(ar);
for (unsigned i = 0; i < attrs.size(); ++i) {
if (m_userAttributes.find(attrs[i]->getName()) != m_userAttributes.end()) {
@@ -89,7 +91,8 @@ FunctionScope::FunctionScope(FunctionScopePtr orig,
const string &name,
const string &originalName,
StatementPtr stmt,
ModifierExpressionPtr modifiers)
ModifierExpressionPtr modifiers,
bool user)
: BlockScope(name, orig->m_docComment, stmt,
BlockScope::FunctionScope),
m_minParam(orig->m_minParam), m_maxParam(orig->m_maxParam),
@@ -101,19 +104,22 @@ FunctionScope::FunctionScope(FunctionScopePtr orig,
m_overriding(orig->m_overriding), m_volatile(orig->m_volatile),
m_persistent(orig->m_persistent),
m_pseudoMain(orig->m_pseudoMain), m_magicMethod(orig->m_magicMethod),
m_system(orig->m_system), m_inlineable(orig->m_inlineable),
m_sep(orig->m_sep), m_containsThis(orig->m_containsThis),
m_system(!user), m_inlineable(orig->m_inlineable),
m_containsThis(orig->m_containsThis),
m_containsBareThis(orig->m_containsBareThis), m_nrvoFix(orig->m_nrvoFix),
m_inlineAsExpr(orig->m_inlineAsExpr),
m_inlineSameContext(orig->m_inlineSameContext),
m_contextSensitive(orig->m_contextSensitive),
m_directInvoke(orig->m_directInvoke),
m_closureGenerator(orig->m_closureGenerator), m_noLSB(orig->m_noLSB),
m_generator(orig->m_generator),
m_async(orig->m_async),
m_noLSB(orig->m_noLSB),
m_nextLSB(orig->m_nextLSB), m_hasTry(orig->m_hasTry),
m_hasGoto(orig->m_hasGoto), m_localRedeclaring(orig->m_localRedeclaring),
m_redeclaring(orig->m_redeclaring),
m_inlineIndex(orig->m_inlineIndex), m_optFunction(orig->m_optFunction),
m_nextID(0), m_yieldLabelCount(orig->m_yieldLabelCount) {
m_nextID(0), m_yieldLabelCount(orig->m_yieldLabelCount),
m_yieldLabelGen(orig->m_yieldLabelGen) {
init(ar);
m_originalName = originalName;
setParamCounts(ar, m_minParam, m_maxParam);
@@ -202,12 +208,14 @@ FunctionScope::FunctionScope(bool method, const std::string &name,
m_method(method), m_refReturn(reference), m_virtual(false),
m_hasOverride(false), m_perfectVirtual(false), m_overriding(false),
m_volatile(false), m_persistent(false), m_pseudoMain(false),
m_magicMethod(false), m_system(true), m_inlineable(false), m_sep(false),
m_magicMethod(false), m_system(true), m_inlineable(false),
m_containsThis(false), m_containsBareThis(0), m_nrvoFix(true),
m_inlineAsExpr(false), m_inlineSameContext(false),
m_contextSensitive(false),
m_directInvoke(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_generator(false),
m_async(false),
m_noLSB(false), m_nextLSB(false),
m_hasTry(false), m_hasGoto(false), m_localRedeclaring(false),
m_redeclaring(-1), m_inlineIndex(0),
m_optFunction(0) {
@@ -279,6 +287,14 @@ void FunctionScope::setParamSpecs(AnalysisResultPtr ar) {
}
}
bool FunctionScope::hasUserAttr(const char *attr) const {
return m_userAttributes.find(attr) != m_userAttributes.end();
}
bool FunctionScope::isZendParamMode() const {
return m_attributeClassInfo & ClassInfo::ZendParamMode;
}
bool FunctionScope::isPublic() const {
return m_modifiers && m_modifiers->isPublic();
}
@@ -299,6 +315,10 @@ bool FunctionScope::isAbstract() const {
return m_modifiers && m_modifiers->isAbstract();
}
bool FunctionScope::isNative() const {
return hasUserAttr("__native");
}
bool FunctionScope::isFinal() const {
return m_modifiers && m_modifiers->isFinal();
}
@@ -343,35 +363,24 @@ bool FunctionScope::isClosure() const {
return ParserBase::IsClosureName(name());
}
bool FunctionScope::isGenerator() const {
assert(!getOrigGenStmt() ||
(ParserBase::IsContinuationName(name()) &&
m_paramNames.size() == 1 &&
m_paramNames[0] == CONTINUATION_OBJECT_NAME));
return !!getOrigGenStmt();
int FunctionScope::allocYieldLabel() {
assert(m_yieldLabelGen >= 0);
return ++m_yieldLabelCount;
}
bool FunctionScope::hasGeneratorAsBody() const {
MethodStatementPtr stmt = dynamic_pointer_cast<MethodStatement>(getStmt());
return stmt ? !!stmt->getGeneratorFunc() : false;
int FunctionScope::getYieldLabelCount() const {
assert(m_yieldLabelGen >= 0);
return m_yieldLabelCount;
}
bool FunctionScope::isGeneratorFromClosure() const {
bool res = isGenerator() && getOrigGenFS()->isClosure();
assert(!res || getOrigGenFS()->isClosureGenerator());
return res;
int FunctionScope::getYieldLabelGeneration() const {
assert(m_yieldLabelGen >= 0);
return m_yieldLabelGen;
}
MethodStatementRawPtr FunctionScope::getOrigGenStmt() const {
if (!getStmt()) return MethodStatementRawPtr();
MethodStatementPtr m =
dynamic_pointer_cast<MethodStatement>(getStmt());
return m ? m->getOrigGeneratorFunc() : MethodStatementRawPtr();
}
FunctionScopeRawPtr FunctionScope::getOrigGenFS() const {
MethodStatementRawPtr origStmt = getOrigGenStmt();
return origStmt ? origStmt->getFunctionScope() : FunctionScopeRawPtr();
void FunctionScope::resetYieldLabelCount() {
++m_yieldLabelGen;
m_yieldLabelCount = 0;
}
void FunctionScope::setVariableArgument(int reference) {
@@ -530,6 +539,7 @@ bool FunctionScope::mayUseVV() const {
return (inPseudoMain() ||
isVariableArgument() ||
isGenerator() ||
isAsync() ||
variables->getAttribute(VariableTable::ContainsDynamicVariable) ||
variables->getAttribute(VariableTable::ContainsExtract) ||
variables->getAttribute(VariableTable::ContainsCompact) ||
@@ -655,7 +665,8 @@ int FunctionScope::inferParamTypes(AnalysisResultPtr ar, ConstructPtr exp,
/**
* Duplicate the logic of getParamType(i), w/o the mutation
*/
TypePtr paramType(i < m_maxParam ? m_paramTypes[i] : TypePtr());
TypePtr paramType(i < m_maxParam && !isZendParamMode() ?
m_paramTypes[i] : TypePtr());
if (!paramType) paramType = Type::Some;
if (valid && !canSetParamType && i < m_maxParam &&
(!Option::HardTypeHints || !m_paramTypeSpecs[i])) {
@@ -667,8 +678,8 @@ int FunctionScope::inferParamTypes(AnalysisResultPtr ar, ConstructPtr exp,
* expression since it'll just get converted anyways. Doing it this way
* allows us to generate less temporaries along the way.
*/
TypePtr optParamType(
paramType->is(Type::KindOfVariant) ? Type::Some : paramType);
TypePtr optParamType(paramType->is(Type::KindOfVariant) ?
Type::Some : paramType);
expType = param->inferAndCheck(ar, optParamType, false);
} else {
expType = param->inferAndCheck(ar, Type::Some, false);
@@ -775,15 +786,10 @@ void FunctionScope::setParamName(int index, const std::string &name) {
void FunctionScope::setParamDefault(int index, const char* value, int64_t len,
const std::string &text) {
assert(index >= 0 && index < (int)m_paramNames.size());
auto sd = StringData::GetStaticString(value, len);
m_paramDefaults[index] = String(sd);
m_paramDefaults[index] = std::string(value, len);
m_paramDefaultTexts[index] = text;
}
CStrRef FunctionScope::getParamDefault(int index) {
return m_paramDefaults[index];
}
void FunctionScope::addModifier(int mod) {
if (!m_modifiers) {
m_modifiers =
@@ -849,7 +855,7 @@ bool FunctionScope::popReturnType() {
m_prevReturn.reset();
addUpdates(UseKindCallerReturn);
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumRetTypesChanged);
++RescheduleException::s_NumRetTypesChanged;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
return true;
}
@@ -923,28 +929,6 @@ std::string FunctionScope::getDocFullName() const {
return docName;
}
std::string FunctionScope::getInjectionId() const {
string injectionName = CodeGenerator::FormatLabel(getOriginalName());
MethodStatementPtr stmt =
dynamic_pointer_cast<MethodStatement>(getStmt());
assert(stmt);
if (stmt->getGeneratorFunc()) {
injectionName = isClosureGenerator() ?
injectionName :
injectionName + "{continuation}";
} else if (stmt->getOrigGeneratorFunc() &&
!getOrigGenFS()->isClosure()) {
injectionName = CodeGenerator::FormatLabel(
stmt->getOrigGeneratorFunc()->getOriginalName());
}
if (m_redeclaring < 0) {
return injectionName;
}
const string &redecSuffix = string(Option::IdPrefix) +
boost::lexical_cast<std::string>(m_redeclaring);
return injectionName + redecSuffix;
}
///////////////////////////////////////////////////////////////////////////////
void FunctionScope::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
@@ -1070,7 +1054,7 @@ bool FunctionScope::needsAnonClosureClass(ParameterExpressionPtrVec &useVars) {
useVars.clear();
if (!isClosure()) return false;
ParameterExpressionPtrIdxPairVec useVars0;
getClosureUseVars(useVars0, !m_closureGenerator);
getClosureUseVars(useVars0, !m_generator && !m_async);
useVars.resize(useVars0.size());
// C++ seems to be unable to infer the type here on pair_first_elem
transform(useVars0.begin(),
@@ -1084,7 +1068,7 @@ bool FunctionScope::needsAnonClosureClass(
ParameterExpressionPtrIdxPairVec &useVars) {
useVars.clear();
if (!isClosure()) return false;
getClosureUseVars(useVars, !m_closureGenerator);
getClosureUseVars(useVars, !m_generator && !m_async);
return useVars.size() > 0 || getVariables()->hasStaticLocals();
}
+22 -24
Ver Arquivo
@@ -22,7 +22,7 @@
#include "hphp/compiler/option.h"
#include "hphp/util/json.h"
#include "hphp/util/parser/parser.h"
#include "hphp/parser/parser.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -73,7 +73,7 @@ public:
FunctionScope(FunctionScopePtr orig, AnalysisResultConstPtr ar,
const std::string &name, const std::string &originalName,
StatementPtr stmt, ModifierExpressionPtr modifiers);
StatementPtr stmt, ModifierExpressionPtr modifiers, bool user);
/**
* System functions.
@@ -84,22 +84,24 @@ public:
void setParamName(int index, const std::string &name);
void setParamDefault(int index, const char* value, int64_t len,
const std::string &text);
CStrRef getParamDefault(int index);
void setRefParam(int index);
bool hasRefParam(int max) const;
void addModifier(int mod);
bool hasUserAttr(const char *attr) const;
/**
* What kind of function this is.
*/
bool isUserFunction() const { return !m_system;}
bool isUserFunction() const { return !m_system && !isNative(); }
bool isDynamic() const { return m_dynamic; }
bool isPublic() const;
bool isProtected() const;
bool isPrivate() const;
bool isStatic() const;
bool isAbstract() const;
bool isNative() const;
bool isFinal() const;
bool isMagic() const;
bool isRefParam(int index) const;
@@ -109,20 +111,18 @@ public:
bool hasImpl() const;
void setDirectInvoke() { m_directInvoke = true; }
bool hasDirectInvoke() const { return m_directInvoke; }
bool isZendParamMode() const;
bool mayContainThis();
bool isClosure() const;
bool isGenerator() const;
bool isGeneratorFromClosure() const;
int allocYieldLabel() { return ++m_yieldLabelCount; }
int getYieldLabelCount() const { return m_yieldLabelCount; }
bool hasGeneratorAsBody() const;
MethodStatementRawPtr getOrigGenStmt() const;
FunctionScopeRawPtr getOrigGenFS() const;
void setClosureGenerator() { m_closureGenerator = true; }
bool isClosureGenerator() const {
assert(!m_closureGenerator || isClosure());
return m_closureGenerator;
}
bool isGenerator() const { return m_generator; }
void setGenerator(bool f) { m_generator = f; }
int allocYieldLabel();
int getYieldLabelCount() const;
int getYieldLabelGeneration() const;
void resetYieldLabelCount();
bool isAsync() const { return m_async; }
void setAsync(bool f) { m_async = f; }
bool needsClassParam();
void setInlineSameContext(bool f) { m_inlineSameContext = f; }
@@ -158,7 +158,6 @@ public:
}
virtual std::string getId() const;
std::string getInjectionId() const;
int getRedeclaringId() const {
return m_redeclaring;
@@ -254,6 +253,8 @@ public:
/**
* What is the inferred type of this function's return.
* Note that for generators and async functions, this is different
* from what caller actually gets when calling the function.
*/
void pushReturnType();
void setReturnType(AnalysisResultConstPtr ar, TypePtr type);
@@ -308,10 +309,6 @@ public:
bool isInlined() const { return m_inlineable; }
void disableInline() { m_inlineable = false; }
/* Whether this function is brought in by a separable extension */
void setSepExtension() { m_sep = true;}
bool isSepExtension() const { return m_sep;}
/* Whether we need to worry about the named return value optimization
for this function */
void setNRVOFix(bool flag) { m_nrvoFix = flag; }
@@ -440,7 +437,7 @@ private:
std::vector<std::string> m_paramNames;
TypePtrVec m_paramTypes;
TypePtrVec m_paramTypeSpecs;
std::vector<String> m_paramDefaults;
std::vector<std::string> m_paramDefaults;
std::vector<std::string> m_paramDefaultTexts;
std::vector<bool> m_refs;
TypePtr m_returnType;
@@ -463,7 +460,6 @@ private:
unsigned m_magicMethod : 1;
unsigned m_system : 1;
unsigned m_inlineable : 1;
unsigned m_sep : 1;
unsigned m_containsThis : 1; // contains a usage of $this?
unsigned m_containsBareThis : 2; // $this outside object-context,
// 2 if in reference context
@@ -472,7 +468,8 @@ private:
unsigned m_inlineSameContext : 1;
unsigned m_contextSensitive : 1;
unsigned m_directInvoke : 1;
unsigned m_closureGenerator : 1;
unsigned m_generator : 1;
unsigned m_async : 1;
unsigned m_noLSB : 1;
unsigned m_nextLSB : 1;
unsigned m_hasTry : 1;
@@ -489,6 +486,7 @@ private:
ReadWriteMutex m_inlineMutex;
unsigned m_nextID; // used when cloning generators for traits
int m_yieldLabelCount; // number of allocated yield labels
int m_yieldLabelGen; // generation counter for yield labels
std::list<FunctionScopeRawPtr> m_clonedTraitOuterScope;
};
+3 -3
Ver Arquivo
@@ -14,9 +14,10 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/expression.h"
@@ -465,7 +466,6 @@ bool LiveDict::color(TypePtr type) {
if (sym &&
!sym->isGlobal() &&
!sym->isParameter() &&
!sym->isGeneratorParameter() &&
!sym->isClosureVar() &&
!sym->isStatic() &&
!e->isThis()) {
@@ -610,7 +610,7 @@ public:
SimpleVariablePtr sv(static_pointer_cast<SimpleVariable>(e));
Symbol *sym = sv->getSymbol();
if (!sym || sym->isGlobal() || sym->isStatic() || sym->isParameter() ||
sym->isGeneratorParameter() || sym->isClosureVar() || sv->isThis()) {
sym->isClosureVar() || sv->isThis()) {
continue;
}
+17 -17
Ver Arquivo
@@ -14,9 +14,9 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
@@ -29,7 +29,7 @@
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
using std::vector;
@@ -74,10 +74,10 @@ void RefDict::visit(ExpressionPtr e) {
SimpleVariablePtr ptr(static_pointer_cast<SimpleVariable>(e));
if (ptr->isSuperGlobal() || ptr->isThis()) {
// don't both recording for super globals or this
// don't both recording for super globals or this
return;
}
// Good to go
if (m_am.insertForDict(e)) {
record(e);
@@ -129,7 +129,7 @@ void RefDict::updateParams() {
bool isRef;
if (sym->isParameter()) {
ExpressionListPtr methodParams = m_method_stmt->getParams();
ExpressionPtr paramExprPtr =
ExpressionPtr paramExprPtr =
(*methodParams)[sym->getParameterIndex()];
paramType = paramExprPtr->getType();
isRef = m_method_stmt->isRef(sym->getParameterIndex());
@@ -160,7 +160,7 @@ void RefDict::updateParams() {
void RefDict::updateAccess(ExpressionPtr e) {
always_assert(!e->getScope()->inPseudoMain());
int eid = e->getCanonID();
int context = e->getContext();
@@ -204,7 +204,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
context & Expression::UnsetContext) {
BitOps::set_bit(eid, m_referenced, false);
BitOps::set_bit(eid, m_killed, true);
}
}
if (first_pass) return;
@@ -215,7 +215,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
// we dealt with this node as a store expression
return;
}
int cls = e->getExprClass();
bool isRhsNeeded = false;
@@ -227,7 +227,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
if (cls & Expression::Store) {
// we care about two cases here
switch (e->getKindOf()) {
case Expression::KindOfAssignmentExpression:
case Expression::KindOfAssignmentExpression:
// $x = ...
{
AssignmentExpressionPtr assign(
@@ -254,7 +254,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
break;
}
}
bool isLhsSimpleVar = false;
bool isLhsDynamic = false;
bool isRefd = false;
@@ -343,20 +343,20 @@ void RefDict::updateAccess(ExpressionPtr e) {
// unset($x);
BitOps::set_bit(eid, m_obj, false);
BitOps::set_bit(eid, m_noobj, true);
} else if (isRefd ||
} else if (isRefd ||
((context & Expression::Declaration) == Expression::Declaration)) {
// if a simple variable has isRefd, then we need to mark it
// as potentially containing an object.
// also, if the simple variable is in global context
// also, if the simple variable is in global context
// then we also mark it as potentially containing an object
BitOps::set_bit(eid, m_obj, true);
BitOps::set_bit(eid, m_noobj, false);
}
}
}
if (isRefd) {
// do a scan for every simple variable referenced value
// in the dictionary and mark it as potentially
// do a scan for every simple variable referenced value
// in the dictionary and mark it as potentially
// containing an object (in the bit vector)
for (int i = size(); i--; ) {
if (ExpressionPtr e = get(i)) {
@@ -372,8 +372,8 @@ void RefDict::updateAccess(ExpressionPtr e) {
}
int RefDictWalker::after(ConstructRawPtr cp) {
if (SimpleVariableRawPtr s =
boost::dynamic_pointer_cast<SimpleVariable>(cp)) {
if (SimpleVariableRawPtr s =
dynamic_pointer_cast<SimpleVariable>(cp)) {
if (int id = s->getCanonID()) {
if (first_pass) {
if (s->isAvailable() && m_block->getBit(DataFlow::PRefIn, id)) {
+5 -16
Ver Arquivo
@@ -27,9 +27,9 @@
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/variable_serializer.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/util/logger.h"
@@ -65,13 +65,13 @@ TypePtr Symbol::setType(AnalysisResultConstPtr ar, BlockScopeRawPtr scope,
// at this point, you *must* have a lock (if you are user scope)
if (scope->is(BlockScope::FunctionScope)) {
FunctionScopeRawPtr f =
boost::static_pointer_cast<FunctionScope>(scope);
static_pointer_cast<FunctionScope>(scope);
if (f->isUserFunction()) {
f->getInferTypesMutex().assertOwnedBySelf();
}
} else if (scope->is(BlockScope::ClassScope)) {
ClassScopeRawPtr c =
boost::static_pointer_cast<ClassScope>(scope);
static_pointer_cast<ClassScope>(scope);
if (c->isUserClass()) {
c->getInferTypesMutex().assertOwnedBySelf();
}
@@ -520,17 +520,6 @@ ConstructPtr SymbolTable::getValue(const std::string &name) const {
return ConstructPtr();
}
void SymbolTable::setSepExtension(const std::string &name) {
genSymbol(name, m_const)->setSep();
}
bool SymbolTable::isSepExtension(const std::string &name) const {
if (const Symbol *sym = getSymbol(name)) {
return sym->isSep();
}
return false;
}
TypePtr SymbolTable::setType(AnalysisResultConstPtr ar, const std::string &name,
TypePtr type, bool coerced) {
return setType(ar, genSymbol(name, m_const), type, coerced);
+2 -15
Ver Arquivo
@@ -74,9 +74,7 @@ public:
void setReplaced() { m_flags.m_replaced = true; }
bool valueSet() const { return m_flags.m_value_set; }
bool isSystem() const { return m_flags.m_system; }
bool isSep() const { return m_flags.m_sep; }
void setSystem() { m_flags.m_system = true; }
void setSep() { m_flags.m_sep = true; }
bool isConstant() const { return m_flags.m_constant; }
void setConstant() { m_flags.m_constant = true; }
@@ -115,8 +113,6 @@ public:
bool isIndirectAltered() const { return m_flags.m_indirectAltered; }
bool isReferenced() const { return !m_flags.m_notReferenced; }
bool isHidden() const { return m_flags.m_hidden; }
bool isGeneratorParameter() const { return m_flags.m_generatorParameter; }
bool isRefGeneratorParameter() const { return m_flags.m_refGeneratorParameter; }
bool isClosureVar() const { return m_flags.m_closureVar; }
bool isRefClosureVar() const { return m_flags.m_refClosureVar; }
bool isPassClosureVar() const { return m_flags.m_passClosureVar; }
@@ -142,8 +138,6 @@ public:
void setIndirectAltered() { m_flags.m_indirectAltered = true; }
void setReferenced() { m_flags.m_notReferenced = false; }
void setHidden() { m_flags.m_hidden = true; }
void setGeneratorParameter() { m_flags.m_generatorParameter = true; }
void setRefGeneratorParameter() { m_flags.m_refGeneratorParameter = true; }
void setClosureVar() { m_flags.m_closureVar = true; }
void setRefClosureVar() { m_flags.m_refClosureVar = true; }
void setPassClosureVar() { m_flags.m_passClosureVar = true; }
@@ -189,7 +183,7 @@ private:
std::string m_name;
unsigned int m_hash;
union {
uint64_t m_flags_val;
uint32_t m_flags_val;
struct {
/* internal */
unsigned m_declaration_set : 1;
@@ -200,7 +194,6 @@ private:
/* common */
unsigned m_system : 1;
unsigned m_sep : 1;
/* ConstantTable */
unsigned m_dynamic : 1;
@@ -223,8 +216,6 @@ private:
unsigned m_indirectAltered : 1;
unsigned m_notReferenced : 1;
unsigned m_hidden : 1;
unsigned m_generatorParameter : 1;
unsigned m_refGeneratorParameter : 1;
unsigned m_closureVar : 1;
unsigned m_refClosureVar : 1;
unsigned m_passClosureVar : 1;
@@ -281,7 +272,7 @@ private:
/**
* Base class of VariableTable and ConstantTable.
*/
class SymbolTable : public boost::enable_shared_from_this<SymbolTable>,
class SymbolTable : public std::enable_shared_from_this<SymbolTable>,
public JSON::CodeError::ISerializable {
public:
static Mutex AllSymbolTablesMutex;
@@ -347,10 +338,6 @@ public:
ConstructPtr getDeclaration(const std::string &name) const;
ConstructPtr getValue(const std::string &name) const;
/* Whether this constant is brought in by a separable extension */
void setSepExtension(const std::string &name);
bool isSepExtension(const std::string &name) const;
/**
* How big of a hash table for generate C++ switch statements.
*/
+31 -7
Ver Arquivo
@@ -20,7 +20,7 @@
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include <boost/format.hpp>
using namespace HPHP;
@@ -36,6 +36,7 @@ TypePtr Type::Double (new Type(Type::KindOfDouble ));
TypePtr Type::String (new Type(Type::KindOfString ));
TypePtr Type::Array (new Type(Type::KindOfArray ));
TypePtr Type::Object (new Type(Type::KindOfObject ));
TypePtr Type::Resource (new Type(Type::KindOfResource ));
TypePtr Type::Variant (new Type(Type::KindOfVariant ));
TypePtr Type::Numeric (new Type(Type::KindOfNumeric ));
@@ -57,6 +58,8 @@ void Type::InitTypeHintMap() {
assert(s_HHTypeHintTypes.empty());
s_TypeHintTypes["array"] = Type::Array;
s_TypeHintTypes["resource"] = Type::Resource;
s_TypeHintTypes["callable"] = Type::Variant;
s_HHTypeHintTypes["array"] = Type::Array;
s_HHTypeHintTypes["bool"] = Type::Boolean;
@@ -67,6 +70,8 @@ void Type::InitTypeHintMap() {
s_HHTypeHintTypes["double"] = Type::Double;
s_HHTypeHintTypes["float"] = Type::Double;
s_HHTypeHintTypes["string"] = Type::String;
s_HHTypeHintTypes["resource"] = Type::Resource;
s_HHTypeHintTypes["callable"] = Type::Variant;
}
const Type::TypePtrMap &Type::GetTypeHintTypes(bool hhType) {
@@ -79,9 +84,12 @@ void Type::ResetTypeHintTypes() {
}
TypePtr Type::CreateObjectType(const std::string &clsname) {
// For interfaces that support arrays we're pessimistic and
// For interfaces that support primitive types, we're pessimistic and
// we treat it as a Variant
if (interface_supports_array(clsname)) {
if (interface_supports_array(clsname) ||
interface_supports_string(clsname) ||
interface_supports_int(clsname) ||
interface_supports_double(clsname)) {
return Type::Variant;
}
return TypePtr(new Type(KindOfObject, clsname));
@@ -90,9 +98,12 @@ TypePtr Type::CreateObjectType(const std::string &clsname) {
TypePtr Type::GetType(KindOf kindOf, const std::string &clsname /* = "" */) {
assert(kindOf);
if (!clsname.empty()) {
// For interfaces that support arrays we're pessimistic and
// For interfaces that support primitive types we're pessimistic and
// we treat it as a Variant
if (interface_supports_array(clsname)) {
if (interface_supports_array(clsname) ||
interface_supports_string(clsname) ||
interface_supports_int(clsname) ||
interface_supports_double(clsname)) {
return Type::Variant;
}
return TypePtr(new Type(kindOf, clsname));
@@ -107,6 +118,7 @@ TypePtr Type::GetType(KindOf kindOf, const std::string &clsname /* = "" */) {
case KindOfArray: return Type::Array;
case KindOfVariant: return Type::Variant;
case KindOfObject: return Type::Object;
case KindOfResource: return Type::Resource;
case KindOfNumeric: return Type::Numeric;
case KindOfPrimitive: return Type::Primitive;
case KindOfPlusOperand: return Type::PlusOperand;
@@ -193,6 +205,7 @@ bool Type::IsMappedToVariant(TypePtr t) {
case KindOfString :
case KindOfArray :
case KindOfObject :
case KindOfResource:
return false;
default: break;
}
@@ -261,7 +274,8 @@ TypePtr Type::Coerce(AnalysisResultConstPtr ar, TypePtr type1, TypePtr type2) {
if (type1->m_kindOf == KindOfVoid &&
(type2->m_kindOf == KindOfString ||
type2->m_kindOf == KindOfArray ||
type2->m_kindOf == KindOfObject)) {
type2->m_kindOf == KindOfObject ||
type2->m_kindOf == KindOfResource)) {
return type2;
}
if (type2->m_kindOf == KindOfSome ||
@@ -396,6 +410,7 @@ bool Type::HasFastCastMethod(TypePtr t) {
case Type::KindOfString:
case Type::KindOfArray:
case Type::KindOfObject:
case Type::KindOfResource:
return true;
default: break;
}
@@ -441,6 +456,9 @@ string Type::GetFastCastMethod(
case Type::KindOfObject:
type = "Obj";
break;
case Type::KindOfResource:
type = "Res";
break;
default:
type = ""; // make the compiler happy
assert(false);
@@ -536,11 +554,13 @@ bool Type::isSpecificObject() const {
}
bool Type::isNonConvertibleType() const {
return m_kindOf == KindOfObject || m_kindOf == KindOfArray;
return m_kindOf == KindOfObject || m_kindOf == KindOfResource ||
m_kindOf == KindOfArray;
}
bool Type::isNoObjectInvolved() const {
if (couldBe(KindOfObject)
|| couldBe(KindOfResource)
|| couldBe(KindOfArray))
return false;
else
@@ -614,6 +634,7 @@ DataType Type::getDataType() const {
case KindOfString: return HPHP::KindOfString;
case KindOfArray: return HPHP::KindOfArray;
case KindOfObject: return HPHP::KindOfObject;
case KindOfResource: return HPHP::KindOfResource;
case KindOfNumeric:
case KindOfPrimitive:
case KindOfPlusOperand:
@@ -635,6 +656,7 @@ std::string Type::getPHPName() {
switch (m_kindOf) {
case KindOfArray: return "array";
case KindOfObject: return m_name;
case KindOfResource: return "resource";
default: break;
}
return "";
@@ -652,6 +674,7 @@ std::string Type::toString() const {
case KindOfSome: return "Some";
case KindOfAny: return "Any";
case KindOfObject: return string("Object - ") + m_name;
case KindOfResource: return "Resource";
case KindOfNumeric: return "Numeric";
case KindOfPrimitive: return "Primitive";
case KindOfPlusOperand: return "PlusOperand";
@@ -700,6 +723,7 @@ void Type::serialize(JSON::DocTarget::OutputStream &out) const {
}
break;
}
case KindOfResource: s = "resource"; break;
case KindOfNumeric: s = "numeric"; break;
case KindOfPrimitive: s = "primitive"; break;
case KindOfPlusOperand: s = "any"; break;
+3 -1
Ver Arquivo
@@ -19,7 +19,7 @@
#include "hphp/compiler/hphp.h"
#include "hphp/util/json.h"
#include "hphp/util/case_insensitive.h"
#include "hphp/util/case-insensitive.h"
#include "hphp/runtime/base/types.h"
@@ -53,6 +53,7 @@ public:
static const KindOf KindOfString = 0x0080;
static const KindOf KindOfArray = 0x0100;
static const KindOf KindOfObject = 0x0200; // with classname
static const KindOf KindOfResource = 0x0400;
static const KindOf KindOfVariant = 0xFFFF;
/* This bit tells coerce that if the other type
@@ -88,6 +89,7 @@ public:
static TypePtr String;
static TypePtr Array;
static TypePtr Object;
static TypePtr Resource;
static TypePtr Variant;
static TypePtr Numeric;
+27 -17
Ver Arquivo
@@ -27,11 +27,12 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/static_member_expression.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/util/util.h"
#include "hphp/util/parser/location.h"
#include "hphp/util/parser/parser.h"
#include "hphp/parser/location.h"
#include "hphp/parser/parser.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -68,20 +69,31 @@ VariableTable::VariableTable(BlockScope &blockScope)
void VariableTable::getLocalVariableNames(vector<string> &syms) const {
FunctionScopeRawPtr fs = getScopePtr()->getContainingFunction();
bool dollarThisIsSpecial = (fs->getContainingClass() ||
fs->inPseudoMain());
bool dollarThisIsSpecial = fs->getContainingClass() ||
fs->inPseudoMain() ||
// In closures, $this is "sometimes"
// special (if it's a closure in a method
// body), but it easiest to just always
// treat it special.
fs->isClosure();
bool hadThisSym = false;
for (unsigned int i = 0; i < m_symbolVec.size(); i++) {
const string& name = m_symbolVec[i]->getName();
if (name == "this" && dollarThisIsSpecial) {
// The "this" variable in methods and pseudo-main is special and is
// handled separately below.
/*
* The "this" variable in methods, pseudo-main, or closures is
* special and is handled separately below.
*
* Closures are the specialest.
*/
hadThisSym = true;
continue;
}
syms.push_back(name);
}
if (fs->needsLocalThis()) {
if (fs->needsLocalThis() || (hadThisSym && fs->isClosure())) {
assert(dollarThisIsSpecial);
// We only need a local variable named "this" if the current function
// contains an occurrence of "$this" that is not part of a property
@@ -178,8 +190,6 @@ bool VariableTable::isLocal(const Symbol *sym) const {
*/
return (!sym->isStatic() &&
!sym->isGlobal() &&
!sym->isGeneratorParameter() &&
!sym->isRefGeneratorParameter() &&
!sym->isParameter());
}
return false;
@@ -292,8 +302,7 @@ void VariableTable::addStaticVariable(Symbol *sym,
m_hasStatic = true;
FunctionScopeRawPtr funcScope = getFunctionScope();
if (funcScope &&
(funcScope->isClosure() || funcScope->isGeneratorFromClosure())) {
if (funcScope && funcScope->isClosure()) {
// static variables for closures/closure generators are local to the
// function scope
m_staticLocalsVec.push_back(sym);
@@ -417,7 +426,12 @@ TypePtr VariableTable::add(Symbol *sym, TypePtr type,
}
type = setType(ar, sym, type, true);
sym->setDeclaration(construct);
if (sym->isParameter()) {
auto p = dynamic_pointer_cast<ParameterExpression>(construct);
if (p) sym->setDeclaration(construct);
} else {
sym->setDeclaration(construct);
}
if (!implicit && m_blockScope.isFirstPass()) {
if (!sym->getValue()) {
@@ -569,10 +583,6 @@ void VariableTable::clearUsed() {
} else {
sym.second.setReferenced();
}
if (sym.second.isRefGeneratorParameter()) {
sym.second.setReferenced();
}
}
}
+38 -19
Ver Arquivo
@@ -27,12 +27,12 @@
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/array/array_iterator.h"
#include "hphp/runtime/base/execution_context.h"
#include "hphp/runtime/base/thread_init_fini.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/array-iterator.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/thread-init-fini.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.h"
#include <dlfcn.h>
@@ -109,12 +109,20 @@ static TypePtr typePtrFromDataType(DataType dt, TypePtr unknown) {
case KindOfString: return Type::String;
case KindOfArray: return Type::Array;
case KindOfObject: return Type::Object;
case KindOfResource: return Type::Resource;
case KindOfUnknown:
default:
return unknown;
}
}
const StaticString
s_fb_call_user_func_safe("fb_call_user_func_safe"),
s_fb_call_user_func_safe_return("fb_call_user_func_safe_return"),
s_fb_call_user_func_array_safe("fb_call_user_func_array_safe"),
s_is_callable("is_callable"),
s_call_user_func_array("call_user_func_array");
FunctionScopePtr BuiltinSymbols::ImportFunctionScopePtr(AnalysisResultPtr ar,
ClassInfo *cls, ClassInfo::MethodInfo *method) {
int attrs = method->attribute;
@@ -155,19 +163,17 @@ FunctionScopePtr BuiltinSymbols::ImportFunctionScopePtr(AnalysisResultPtr ar,
}
f->setClassInfoAttribute(attrs);
if (attrs & ClassInfo::HasDocComment) {
f->setDocComment(method->docComment);
}
f->setDocComment(method->docComment);
if (!isMethod && (attrs & ClassInfo::HasOptFunction)) {
// Legacy optimization functions
if (method->name.same("fb_call_user_func_safe") ||
method->name.same("fb_call_user_func_safe_return") ||
method->name.same("fb_call_user_func_array_safe")) {
if (method->name.same(s_fb_call_user_func_safe) ||
method->name.same(s_fb_call_user_func_safe_return) ||
method->name.same(s_fb_call_user_func_array_safe)) {
f->setOptFunction(hphp_opt_fb_call_user_func);
} else if (method->name.same("is_callable")) {
} else if (method->name.same(s_is_callable)) {
f->setOptFunction(hphp_opt_is_callable);
} else if (method->name.same("call_user_func_array")) {
} else if (method->name.same(s_call_user_func_array)) {
f->setOptFunction(hphp_opt_call_user_func);
}
}
@@ -216,6 +222,11 @@ void BuiltinSymbols::ImportExtFunctions(AnalysisResultPtr ar,
ClassInfo *cls) {
const ClassInfo::MethodVec &methods = cls->getMethodsVec();
for (auto it = methods.begin(); it != methods.end(); ++it) {
if (((*it)->attribute & ClassInfo::ZendCompat) &&
!Option::EnableZendCompat) {
continue;
}
FunctionScopePtr f = ImportFunctionScopePtr(ar, cls, *it);
assert(!map[f->getName()]);
map[f->getName()] = f;
@@ -263,7 +274,7 @@ void BuiltinSymbols::ImportExtConstants(AnalysisResultPtr ar,
for (auto it = src.begin(); it != src.end(); ++it) {
// We make an assumption that if the constant is a callback type
// (e.g. STDIN, STDOUT, STDERR) then it will return an Object.
// And that if it's deferred (SID, PHP_SAPI) it'll be a String.
// And that if it's deferred (SID, PHP_SAPI, etc.) it'll be a String.
ClassInfo::ConstantInfo *cinfo = *it;
dest->add(cinfo->name.data(),
cinfo->isDeferred() ?
@@ -298,9 +309,7 @@ ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
ImportExtConstants(ar, cl->getConstants(), cls);
int attrs = cls->getAttribute();
cl->setClassInfoAttribute(attrs);
if (attrs & ClassInfo::HasDocComment) {
cl->setDocComment(cls->getDocComment());
}
cl->setDocComment(cls->getDocComment());
cl->setSystem();
return cl;
}
@@ -308,6 +317,13 @@ ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
void BuiltinSymbols::ImportExtClasses(AnalysisResultPtr ar) {
const ClassInfo::ClassMap &classes = ClassInfo::GetClassesMap();
for (auto it = classes.begin(); it != classes.end(); ++it) {
const ClassInfo *info = it->second;
if ((info->getAttribute() & ClassInfo::ZendCompat) &&
!Option::EnableZendCompat) {
continue;
}
ClassScopePtr cl = ImportClassScopePtr(ar, it->second);
assert(!s_classes[cl->getName()]);
s_classes[cl->getName()] = cl;
@@ -357,8 +373,11 @@ bool BuiltinSymbols::Load(AnalysisResultPtr ar) {
ConstructPtr(), ModifierExpressionPtr());
}
s_constants->setDynamic(ar, "SID", true);
s_constants->setDynamic(ar, "PHP_BINARY", true);
s_constants->setDynamic(ar, "PHP_BINDIR", true);
s_constants->setDynamic(ar, "PHP_OS", true);
s_constants->setDynamic(ar, "PHP_SAPI", true);
s_constants->setDynamic(ar, "SID", true);
// parse all PHP files under system/php
s_systemAr = ar = AnalysisResultPtr(new AnalysisResult());
+2 -2
Ver Arquivo
@@ -18,8 +18,8 @@
#define incl_HPHP_BUILTIN_SYMBOLS_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/string_bag.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/util/string-bag.h"
#include "hphp/runtime/base/class-info.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+14 -13
Ver Arquivo
@@ -27,22 +27,22 @@
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/util/json.h"
#include "hphp/util/logger.h"
#include "hphp/util/db_conn.h"
#include "hphp/util/db-conn.h"
#include "hphp/util/exception.h"
#include "hphp/util/process.h"
#include "hphp/util/util.h"
#include "hphp/util/timer.h"
#include "hphp/util/hdf.h"
#include "hphp/util/async_func.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/memory/smart_allocator.h"
#include "hphp/util/async-func.h"
#include "hphp/util/current-executable.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/externals.h"
#include "hphp/runtime/base/thread_init_fini.h"
#include "hphp/runtime/base/thread-init-fini.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/system/systemlib.h"
#include "hphp/util/repo_schema.h"
#include "hphp/util/repo-schema.h"
#include "hphp/hhvm/process_init.h"
#include "hphp/hhvm/process-init.h"
#include <sys/types.h>
#include <sys/wait.h>
@@ -359,7 +359,7 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
#endif
#define HPHP_VERSION(v) cout << HPHP_COMPILER_STR #v << "\n";
#include "../version"
#include "../version" // nolint
cout << "Compiler: " << kCompilerId << "\n";
cout << "Repo schema: " << kRepoSchemaId << "\n";
@@ -804,6 +804,7 @@ void hhbcTargetInit(const CompilerOptions &po, AnalysisResultPtr ar) {
RuntimeOption::RepoDebugInfo = Option::RepoDebugInfo;
RuntimeOption::RepoJournal = "memory";
RuntimeOption::EnableHipHopSyntax = Option::EnableHipHopSyntax;
RuntimeOption::EnableZendCompat = Option::EnableZendCompat;
RuntimeOption::EvalJitEnableRenameFunction = Option::JitEnableRenameFunction;
// Turn off commits, because we don't want systemlib to get included
@@ -866,11 +867,11 @@ int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
*/
string exe = po.outputDir + '/' + po.program;
string repo = "repo=" + exe + ".hhbc";
char buf[PATH_MAX];
if (!realpath("/proc/self/exe", buf)) return -1;
string buf = current_executable_path();
if (buf.empty()) return -1;
const char *argv[] = { "objcopy", "--add-section", repo.c_str(),
buf, exe.c_str(), 0 };
buf.c_str(), exe.c_str(), 0 };
string out;
ret = Process::Exec(argv[0], argv, nullptr, out, nullptr) ? 0 : 1;
}
@@ -909,8 +910,8 @@ int runTarget(const CompilerOptions &po) {
// run the executable
string cmd;
if (po.format.find("exe") == string::npos) {
char buf[PATH_MAX];
if (!realpath("/proc/self/exe", buf)) return -1;
string buf = current_executable_path();
if (buf.empty()) return -1;
cmd += buf;
cmd += " -vRepo.Authoritative=true";
+2 -2
Ver Arquivo
@@ -44,7 +44,7 @@ void Construct::resetScope(BlockScopeRawPtr scope, bool resetOrigScope) {
setBlockScope(scope);
if (resetOrigScope) {
ExpressionPtr expr =
boost::dynamic_pointer_cast<Expression>(shared_from_this());
dynamic_pointer_cast<Expression>(shared_from_this());
if (expr) {
expr->setOriginalScope(scope);
}
@@ -439,7 +439,7 @@ public:
// HACK: dump the closure function as a "child" of the
// closure expression
ClosureExpressionPtr c =
boost::dynamic_pointer_cast<ClosureExpression>(cp);
dynamic_pointer_cast<ClosureExpression>(cp);
if (c) {
c->getClosureFunction()->dump(m_spc, m_ar);
}
+10 -5
Ver Arquivo
@@ -67,7 +67,7 @@ public:
/**
* Base class of Expression and Statement.
*/
class Construct : public boost::enable_shared_from_this<Construct>,
class Construct : public std::enable_shared_from_this<Construct>,
public JSON::CodeError::ISerializable {
protected:
Construct(BlockScopePtr scope, LocationPtr loc);
@@ -166,6 +166,10 @@ public:
void clearKilled() { m_flags.killed = false; }
bool isKilled() const { return m_flags.killed; }
void setChildOfYield() { m_flags.childOfYield = true; }
void clearChildOfYield() { m_flags.childOfYield = false; }
bool isChildOfYield() const { return m_flags.childOfYield; }
BlockScopeRawPtr getScope() const { return m_blockScope; }
void setBlockScope(BlockScopeRawPtr scope) { m_blockScope = scope; }
FileScopeRawPtr getFileScope() const {
@@ -187,15 +191,15 @@ public:
virtual bool kidUnused(int i) const { return false; }
template<typename T>
static boost::shared_ptr<T> Clone(boost::shared_ptr<T> constr) {
static std::shared_ptr<T> Clone(std::shared_ptr<T> constr) {
if (constr) {
return boost::dynamic_pointer_cast<T>(constr->clone());
return dynamic_pointer_cast<T>(constr->clone());
}
return boost::shared_ptr<T>();
return std::shared_ptr<T>();
}
template<typename T>
boost::shared_ptr<T> Clone(boost::shared_ptr<T> constr, BlockScopePtr scope) {
std::shared_ptr<T> Clone(std::shared_ptr<T> constr, BlockScopePtr scope) {
if (constr) {
constr = constr->clone();
constr->resetScope(scope);
@@ -295,6 +299,7 @@ private:
unsigned killed : 1;
unsigned refCounted : 2; // high bit indicates whether its valid
unsigned inited : 2; // high bit indicates whether its valid
unsigned childOfYield : 1; // parent node is yield
} m_flags;
};
protected:
@@ -22,9 +22,9 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/static_member_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -217,10 +217,10 @@ int ArrayElementExpression::getKidCount() const {
void ArrayElementExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_variable = boost::dynamic_pointer_cast<Expression>(cp);
m_variable = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_offset = boost::dynamic_pointer_cast<Expression>(cp);
m_offset = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -17,7 +17,7 @@
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -94,10 +94,10 @@ int ArrayPairExpression::getKidCount() const {
void ArrayPairExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_name = boost::dynamic_pointer_cast<Expression>(cp);
m_name = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_value = boost::dynamic_pointer_cast<Expression>(cp);
m_value = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -25,15 +25,15 @@
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -160,10 +160,10 @@ int AssignmentExpression::getKidCount() const {
void AssignmentExpression::setNthKid(int n, ConstructPtr cp) {
switch (m_rhsFirst ? 1 - n : n) {
case 0:
m_variable = boost::dynamic_pointer_cast<Expression>(cp);
m_variable = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_value = boost::dynamic_pointer_cast<Expression>(cp);
m_value = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -180,11 +180,11 @@ bool AssignmentExpression::isSimpleGlobalAssign(StringData **name,
Variant v;
if (!m_value->getScalarValue(v) || v.is(KindOfArray)) return false;
if (name) {
*name = StringData::GetStaticString(ae->getGlobalName());
*name = makeStaticString(ae->getGlobalName());
}
if (tv) {
if (v.isString()) {
v = StringData::GetStaticString(v.toCStrRef().get());
v = makeStaticString(v.toCStrRef().get());
}
*tv = *v.asTypedValue();
}
@@ -0,0 +1,92 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
AwaitExpression::AwaitExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr exp)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(AwaitExpression)),
m_exp(exp), m_label(this) {
}
ExpressionPtr AwaitExpression::clone() {
AwaitExpressionPtr exp(new AwaitExpression(*this));
Expression::deepCopy(exp);
exp->m_exp = Clone(m_exp);
exp->m_label.setExpression(exp.get());
return exp;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
void AwaitExpression::analyzeProgram(AnalysisResultPtr ar) {
assert(getFunctionScope() && getFunctionScope()->isAsync());
m_exp->analyzeProgram(ar);
m_label.setNew();
}
ConstructPtr AwaitExpression::getNthKid(int n) const {
switch (n) {
case 0:
return m_exp;
default:
assert(false);
break;
}
return ConstructPtr();
}
int AwaitExpression::getKidCount() const {
return 1;
}
void AwaitExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
break;
}
}
TypePtr AwaitExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
m_exp->inferAndCheck(ar, Type::Some, false);
return Type::Variant;
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void AwaitExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
cg_printf("await ");
m_exp->outputPHP(cg, ar);
}
+46
Ver Arquivo
@@ -0,0 +1,46 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_AWAIT_EXPRESSION_H_
#define incl_HPHP_AWAIT_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/generation_label.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(AwaitExpression);
class AwaitExpression : public Expression {
public:
AwaitExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr exp);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
ExpressionPtr getExpression() { return m_exp; }
GenerationLabel& label() { return m_label; }
private:
ExpressionPtr m_exp;
GenerationLabel m_label;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_AWAIT_EXPRESSION_H_
+29 -12
Ver Arquivo
@@ -18,20 +18,20 @@
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/comparisons.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/encaps_list_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/statement/loop_statement.h"
#include "hphp/runtime/base/tv_arith.h"
#include "hphp/runtime/base/tv-arith.h"
using namespace HPHP;
@@ -243,10 +243,10 @@ int BinaryOpExpression::getKidCount() const {
void BinaryOpExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp1 = boost::dynamic_pointer_cast<Expression>(cp);
m_exp1 = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_exp2 = boost::dynamic_pointer_cast<Expression>(cp);
m_exp2 = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -598,10 +598,27 @@ ExpressionPtr BinaryOpExpression::foldConst(AnalysisResultConstPtr ar) {
case T_LOGICAL_AND:
result = v1.toBoolean() && v2.toBoolean(); break;
case T_INSTANCEOF: {
if (v1.isArray() && v2.isString() &&
interface_supports_array(v2.getStringData())) {
result = true;
break;
if (v2.isString()) {
if (v1.isArray() &&
interface_supports_array(v2.getStringData())) {
result = true;
break;
}
if (v1.isString() &&
interface_supports_string(v2.getStringData())) {
result = true;
break;
}
if (v1.isInteger() &&
interface_supports_int(v2.getStringData())) {
result = true;
break;
}
if (v1.isDouble() &&
interface_supports_double(v2.getStringData())) {
result = true;
break;
}
}
result = false;
break;
@@ -108,7 +108,7 @@ int ClassConstantExpression::getKidCount() const {
void ClassConstantExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_class = boost::dynamic_pointer_cast<Expression>(cp);
m_class = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
+1 -6
Ver Arquivo
@@ -61,11 +61,6 @@ ClosureExpression::ClosureExpression
ParameterExpressionPtr param(
dynamic_pointer_cast<ParameterExpression>((*vars)[i]));
assert(param);
if (param->getName() == "this") {
// "this" is automatically included.
// Once we get rid of all the callsites, make this an error
continue;
}
if (seenBefore.find(param->getName().c_str()) == seenBefore.end()) {
seenBefore.insert(param->getName().c_str());
m_vars->insertElement(param);
@@ -124,7 +119,7 @@ int ClosureExpression::getKidCount() const {
void ClosureExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_values = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_values = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
@@ -40,12 +40,16 @@ public:
FunctionStatementPtr getClosureFunction() { return m_func; }
ExpressionListPtr getClosureVariables() { return m_vars; }
ExpressionListPtr getClosureValues() { return m_values; }
StringData* getClosureClassName() { return m_closureClassName; }
void setClosureClassName(StringData* value) { m_closureClassName = value; }
bool hasStaticLocals();
private:
FunctionStatementPtr m_func;
ExpressionListPtr m_vars;
ExpressionListPtr m_values;
StringData* m_closureClassName;
static TypePtr s_ClosureType;
@@ -26,7 +26,7 @@
#include "hphp/util/util.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/runtime/ext/ext_misc.h"
+1 -1
Ver Arquivo
@@ -66,7 +66,7 @@ int DynamicVariable::getKidCount() const {
void DynamicVariable::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = boost::dynamic_pointer_cast<Expression>(cp);
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -18,7 +18,7 @@
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -70,7 +70,7 @@ int EncapsListExpression::getKidCount() const {
void EncapsListExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exps = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_exps = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
+13 -3
Ver Arquivo
@@ -17,7 +17,7 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/util/util.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
@@ -30,12 +30,13 @@
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/function_call.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/util/hash.h"
#include "hphp/runtime/base/array/array_iterator.h"
#include "hphp/runtime/base/array-iterator.h"
using namespace HPHP;
@@ -70,6 +71,7 @@ ExpressionPtr Expression::replaceValue(ExpressionPtr rep) {
rep->clearContext(AssignmentRHS);
rep = el;
}
if (isChildOfYield()) rep->setChildOfYield();
if (rep->is(KindOfSimpleVariable) && !is(KindOfSimpleVariable)) {
static_pointer_cast<SimpleVariable>(rep)->setAlwaysStash();
}
@@ -368,7 +370,7 @@ void Expression::setTypes(AnalysisResultConstPtr ar, TypePtr actualType,
}
if (m_actualType->isSpecificObject()) {
boost::const_pointer_cast<AnalysisResult>(ar)->
std::const_pointer_cast<AnalysisResult>(ar)->
addClassDependency(getFileScope(), m_actualType->getName());
}
}
@@ -674,6 +676,14 @@ bool Expression::isArray() const {
return false;
}
bool Expression::isCollection() const {
if (is(KindOfBinaryOpExpression)) {
return
static_cast<const BinaryOpExpression*>(this)->getOp() == T_COLLECTION;
}
return false;
}
bool Expression::isUnquotedScalar() const {
if (!is(KindOfScalarExpression)) return false;
return !((ScalarExpression*)this)->isQuoted();
+3 -1
Ver Arquivo
@@ -76,6 +76,7 @@ class Variant;
x(EncapsListExpression, None), \
x(ClosureExpression, None), \
x(YieldExpression, None), \
x(AwaitExpression, None), \
x(UserAttribute, None)
class Expression : public Construct {
@@ -202,7 +203,7 @@ public:
*/
virtual int getKidCount() const { return 0; }
ExpressionPtr getNthExpr(int n) const { return
boost::static_pointer_cast<Expression>(getNthKid(n)); }
static_pointer_cast<Expression>(getNthKid(n)); }
/**
* For cse & canonicalization
@@ -232,6 +233,7 @@ public:
virtual bool isTemporary() const { return false; }
virtual bool isScalar() const { return false; }
bool isArray() const;
bool isCollection() const;
virtual bool isRefable(bool checkError = false) const { return false; }
virtual bool getScalarValue(Variant &value) { return false; }
FileScopeRawPtr getUsedScalarScope(CodeGenerator& cg);
+4 -4
Ver Arquivo
@@ -22,7 +22,7 @@
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/runtime/base/array/array_init.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/compiler/parser/parser.h"
using namespace HPHP;
@@ -231,14 +231,14 @@ void ExpressionList::stripConcat() {
for (int i = 0; i < el.getCount(); ) {
ExpressionPtr &e = el[i];
if (e->is(Expression::KindOfUnaryOpExpression)) {
UnaryOpExpressionPtr u(boost::static_pointer_cast<UnaryOpExpression>(e));
UnaryOpExpressionPtr u(static_pointer_cast<UnaryOpExpression>(e));
if (u->getOp() == '(') {
e = u->getExpression();
}
}
if (e->is(Expression::KindOfBinaryOpExpression)) {
BinaryOpExpressionPtr b
(boost::static_pointer_cast<BinaryOpExpression>(e));
(static_pointer_cast<BinaryOpExpression>(e));
if (b->getOp() == '.') {
e = b->getExp1();
el.insertElement(b->getExp2(), i + 1);
@@ -335,7 +335,7 @@ void ExpressionList::setNthKid(int n, ConstructPtr cp) {
if (n >= m) {
assert(false);
} else {
m_exps[n] = boost::dynamic_pointer_cast<Expression>(cp);
m_exps[n] = dynamic_pointer_cast<Expression>(cp);
}
}
+45 -32
Ver Arquivo
@@ -35,7 +35,7 @@
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -120,13 +120,13 @@ int FunctionCall::getKidCount() const {
void FunctionCall::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_class = boost::dynamic_pointer_cast<Expression>(cp);
m_class = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_nameExp = boost::dynamic_pointer_cast<Expression>(cp);
m_nameExp = dynamic_pointer_cast<Expression>(cp);
break;
case 2:
m_params = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_params = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
@@ -171,39 +171,43 @@ void FunctionCall::markRefParams(FunctionScopePtr func,
}
}
void FunctionCall::checkParamTypeCodeErrors(AnalysisResultPtr ar) {
if (!m_funcScope || m_arrayParams) return;
for (int i = 0, n = m_funcScope->getMaxParamCount(); i < n; ++i) {
TypePtr specType = m_funcScope->getParamTypeSpec(i);
if (!specType) continue;
const char *fmt = 0;
string ptype;
if (!m_params || m_params->getCount() <= i) {
if (i >= m_funcScope->getMinParamCount()) break;
fmt = "parameter %d of %s() requires %s, none given";
} else {
ExpressionPtr param = (*m_params)[i];
if (!Type::Inferred(ar, param->getType(), specType)) {
fmt = "parameter %d of %s() requires %s, called with %s";
}
ptype = param->getType()->toString();
}
if (fmt) {
string msg;
Util::string_printf
(msg, fmt,
i + 1,
Util::escapeStringForCPP(m_funcScope->getOriginalName()).c_str(),
specType->toString().c_str(), ptype.c_str());
Compiler::Error(Compiler::BadArgumentType,
shared_from_this(), msg);
}
}
}
void FunctionCall::analyzeProgram(AnalysisResultPtr ar) {
if (m_class) m_class->analyzeProgram(ar);
if (m_nameExp) m_nameExp->analyzeProgram(ar);
if (m_params) m_params->analyzeProgram(ar);
if (ar->getPhase() == AnalysisResult::AnalyzeFinal) {
if (m_funcScope && !m_arrayParams) {
for (int i = 0, n = m_funcScope->getMaxParamCount(); i < n; ++i) {
if (TypePtr specType = m_funcScope->getParamTypeSpec(i)) {
const char *fmt = 0;
string ptype;
if (!m_params || m_params->getCount() <= i) {
if (i >= m_funcScope->getMinParamCount()) break;
fmt = "parameter %d of %s() requires %s, none given";
} else {
ExpressionPtr param = (*m_params)[i];
if (!Type::Inferred(ar, param->getType(), specType)) {
fmt = "parameter %d of %s() requires %s, called with %s";
}
ptype = param->getType()->toString();
}
if (fmt) {
string msg;
Util::string_printf
(msg, fmt,
i + 1,
Util::escapeStringForCPP(m_funcScope->getOriginalName()).c_str(),
specType->toString().c_str(), ptype.c_str());
Compiler::Error(Compiler::BadArgumentType,
shared_from_this(), msg);
}
}
}
}
checkParamTypeCodeErrors(ar);
}
}
@@ -545,6 +549,15 @@ TypePtr FunctionCall::checkParamsAndReturn(AnalysisResultPtr ar,
assert(!func->inVisitScopes() || getScope() == func);
frt = func->getReturnType();
}
// fix return type for generators and async functions here, keep the
// infered return type in function scope to allow further optimizations
if (func->isGenerator()) {
frt = Type::GetType(Type::KindOfObject, "Continuation");
} else if (func->isAsync()) {
frt = Type::GetType(Type::KindOfObject, "WaitHandle");
}
if (!frt) {
m_voidReturn = true;
setActualType(TypePtr());
+3
Ver Arquivo
@@ -65,6 +65,9 @@ public:
bool isValid() const { return m_valid; }
bool hadBackslash() const { return m_hadBackslash; }
private:
void checkParamTypeCodeErrors(AnalysisResultPtr);
protected:
ExpressionPtr m_nameExp;
std::string m_name;
@@ -0,0 +1,49 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/generation_label.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/expression.h"
namespace HPHP {
GenerationLabel::GenerationLabel(Expression* e)
: m_id(-1)
, m_generation(-1)
, m_owner(e)
{}
int GenerationLabel::id() const {
assert(m_id >= 1);
assert(m_generation ==
m_owner->getFunctionScope()->getYieldLabelGeneration());
return m_id;
}
void GenerationLabel::setNew() {
auto func = m_owner->getFunctionScope();
auto newGen = func->getYieldLabelGeneration();
assert(m_generation < newGen);
m_generation = newGen;
m_id = func->allocYieldLabel();
}
void GenerationLabel::setExpression(Expression* e) {
m_owner = e;
}
}
+40
Ver Arquivo
@@ -0,0 +1,40 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_COMPILER_GENERATION_LABEL_H
#define incl_HPHP_COMPILER_GENERATION_LABEL_H
namespace HPHP {
class Expression;
class GenerationLabel {
public:
explicit GenerationLabel(Expression* e);
int id() const;
void setNew();
void setExpression(Expression* e);
private:
int m_id;
int m_generation;
Expression* m_owner;
};
}
#endif
+1 -1
Ver Arquivo
@@ -15,7 +15,7 @@
*/
#include "hphp/compiler/expression/include_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
+10 -5
Ver Arquivo
@@ -23,7 +23,7 @@
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -76,6 +76,7 @@ static ListAssignment::RHSKind GetRHSKind(ExpressionPtr rhs) {
case Expression::KindOfExpressionList:
case Expression::KindOfIncludeExpression:
case Expression::KindOfYieldExpression:
case Expression::KindOfAwaitExpression:
return ListAssignment::Regular;
case Expression::KindOfListAssignment:
@@ -102,8 +103,12 @@ static ListAssignment::RHSKind GetRHSKind(ExpressionPtr rhs) {
case Expression::KindOfBinaryOpExpression: {
BinaryOpExpressionPtr b(static_pointer_cast<BinaryOpExpression>(rhs));
return b->isAssignmentOp() || b->getOp() == '+' ?
ListAssignment::Regular : ListAssignment::Null;
if (b->isAssignmentOp() ||
b->getOp() == '+' ||
b->getOp() == T_COLLECTION) {
return ListAssignment::Regular;
}
return ListAssignment::Null;
}
case Expression::KindOfQOpExpression:
return ListAssignment::Checked;
@@ -238,10 +243,10 @@ int ListAssignment::getKidCount() const {
void ListAssignment::setNthKid(int n, ConstructPtr cp) {
switch (m_rhsFirst ? 1 - n : n) {
case 0:
m_variables = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_variables = dynamic_pointer_cast<ExpressionList>(cp);
break;
case 1:
m_array = boost::dynamic_pointer_cast<Expression>(cp);
m_array = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
+54 -20
Ver Arquivo
@@ -15,7 +15,7 @@
*/
#include "hphp/compiler/expression/modifier_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -24,7 +24,8 @@ using namespace HPHP;
ModifierExpression::ModifierExpression
(EXPRESSION_CONSTRUCTOR_PARAMETERS)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ModifierExpression)) {
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ModifierExpression)),
m_hasPrivacy(true) {
}
ExpressionPtr ModifierExpression::clone() {
@@ -46,11 +47,15 @@ int ModifierExpression::operator[](int index) {
}
bool ModifierExpression::isPublic() const {
if (!m_hasPrivacy) {
return false;
}
for (unsigned int i = 0; i < m_modifiers.size(); i++) {
switch (m_modifiers[i]) {
case T_PUBLIC: return true;
case T_PROTECTED:
case T_PRIVATE: return false;
case T_PRIVATE:
return false;
default:
break;
}
@@ -67,6 +72,10 @@ bool ModifierExpression::hasModifier(int modifier) const {
return false;
}
bool ModifierExpression::isExplicitlyPublic() const {
return hasModifier(T_PUBLIC);
}
bool ModifierExpression::isProtected() const {
return hasModifier(T_PROTECTED);
}
@@ -87,6 +96,28 @@ bool ModifierExpression::isFinal() const {
return hasModifier(T_FINAL);
}
bool ModifierExpression::isAsync() const {
return hasModifier(T_ASYNC);
}
bool ModifierExpression::validForFunction() const {
for (auto i = m_modifiers.begin(); i != m_modifiers.end(); ++i) {
if (*i != T_ASYNC) {
return false;
}
}
return true;
}
bool ModifierExpression::validForClosure() const {
for (auto i = m_modifiers.begin(); i != m_modifiers.end(); ++i) {
if (*i != T_ASYNC && *i != T_STATIC) {
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
@@ -104,21 +135,23 @@ TypePtr ModifierExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
// code generation functions
void ModifierExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
if (m_modifiers.empty()) {
cg_printf("public");
return;
}
bool printed = false;
for (unsigned int i = 0; i < m_modifiers.size(); i++) {
switch (m_modifiers[i]) {
case T_PUBLIC: cg_printf("public"); printed = true; break;
case T_PROTECTED: cg_printf("protected"); printed = true; break;
case T_PRIVATE: cg_printf("private"); printed = true; break;
if (m_hasPrivacy) {
if (m_modifiers.empty()) {
cg_printf("public ");
return;
}
bool printed = false;
for (unsigned int i = 0; i < m_modifiers.size(); i++) {
switch (m_modifiers[i]) {
case T_PUBLIC: cg_printf("public "); printed = true; break;
case T_PROTECTED: cg_printf("protected "); printed = true; break;
case T_PRIVATE: cg_printf("private "); printed = true; break;
}
}
if (!printed) {
cg_printf("public ");
}
}
if (!printed) {
cg_printf("public");
}
for (unsigned int i = 0; i < m_modifiers.size(); i++) {
@@ -126,9 +159,10 @@ void ModifierExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
case T_PUBLIC: break;
case T_PROTECTED: break;
case T_PRIVATE: break;
case T_STATIC: cg_printf(" static"); break;
case T_ABSTRACT: cg_printf(" abstract"); break;
case T_FINAL: cg_printf(" final"); break;
case T_STATIC: cg_printf("static "); break;
case T_ABSTRACT: cg_printf("abstract "); break;
case T_FINAL: cg_printf("final "); break;
case T_ASYNC: cg_printf("async "); break;
default:
assert(false);
}
@@ -34,17 +34,34 @@ public:
int getCount() const { return m_modifiers.size();}
int operator[](int index);
/**
* Whether the modifiers combine to mean public, including the implicit
* public access that occurs when none of public|private|protected are
* supplied.
*/
bool isPublic() const;
/**
* Use isPublic unless you care about the difference between no-modifiers
* implicit public and public-keyword-appears explicitly public.
*/
bool isExplicitlyPublic() const;
bool isProtected() const;
bool isPrivate() const;
bool isStatic() const;
bool isAbstract() const;
bool isFinal() const;
bool isAsync() const;
int getLocalEffects() const { return NoEffect; }
bool validForFunction() const;
bool validForClosure() const;
void setHasPrivacy(bool f) { m_hasPrivacy = f; }
private:
std::vector<int> m_modifiers;
bool m_hasPrivacy;
bool hasModifier(int modifier) const;
};
@@ -116,7 +116,7 @@ ConstructPtr ObjectMethodExpression::getNthKid(int n) const {
void ObjectMethodExpression::setNthKid(int n, ConstructPtr cp) {
if (!n) {
m_object = boost::dynamic_pointer_cast<Expression>(cp);
m_object = dynamic_pointer_cast<Expression>(cp);
} else {
FunctionCall::setNthKid(n, cp);
}
@@ -25,7 +25,7 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/util/hash.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -173,10 +173,10 @@ int ObjectPropertyExpression::getKidCount() const {
void ObjectPropertyExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_object = boost::dynamic_pointer_cast<Expression>(cp);
m_object = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_property = boost::dynamic_pointer_cast<Expression>(cp);
m_property = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -131,7 +131,7 @@ int ParameterExpression::getKidCount() const {
void ParameterExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_defaultValue = boost::dynamic_pointer_cast<Expression>(cp);
m_defaultValue = dynamic_pointer_cast<Expression>(cp);
break;
default:
break;
@@ -144,15 +144,22 @@ TypePtr ParameterExpression::getTypeSpecForClass(AnalysisResultPtr ar,
if (forInference) {
ClassScopePtr cls = ar->findClass(m_type);
if (!cls || cls->isRedeclaring() || cls->derivedByDynamic()) {
if (!cls && getScope()->isFirstPass()) {
if (!cls && getScope()->isFirstPass() && !ar->isTypeAliasName(m_type)) {
ConstructPtr self = shared_from_this();
Compiler::Error(Compiler::UnknownClass, self);
}
ret = Type::Variant;
}
if (cls) {
// Classes must be redeclaring if there are also type aliases
// with the same name.
assert(!ar->isTypeAliasName(m_type) || cls->isRedeclaring());
}
}
if (!ret) {
ret = Type::CreateObjectType(m_type);
ret = ar->isTypeAliasName(m_type) || !Option::WholeProgram
? Type::Variant
: Type::CreateObjectType(m_type);
}
always_assert(ret);
return ret;
@@ -262,6 +269,7 @@ void ParameterExpression::compatibleDefault() {
case KindOfNull: compat = true; break;
/* KindOfClass is an hhvm internal type, can not occur here */
case KindOfObject: /* fall through */
case KindOfResource: /* fall through */
case KindOfRef: assert(false /* likely parser bug */);
default: compat = false; break;
}
+6 -3
Ver Arquivo
@@ -20,7 +20,7 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/util/json.h"
#include "hphp/util/parser/scanner.h"
#include "hphp/parser/scanner.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -33,9 +33,12 @@ DECLARE_BOOST_TYPES(TypeAnnotation);
class ParameterExpression : public Expression {
public:
ParameterExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
TypeAnnotationPtr type, bool hhType,
TypeAnnotationPtr type,
bool hhType,
const std::string &name,
bool ref, TokenID modifier, ExpressionPtr defaultValue,
bool ref,
TokenID modifier,
ExpressionPtr defaultValue,
ExpressionPtr attributeList);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
+4 -4
Ver Arquivo
@@ -16,7 +16,7 @@
#include "hphp/compiler/expression/qop_expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
@@ -75,13 +75,13 @@ int QOpExpression::getKidCount() const {
void QOpExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_condition = boost::dynamic_pointer_cast<Expression>(cp);
m_condition = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_expYes = boost::dynamic_pointer_cast<Expression>(cp);
m_expYes = dynamic_pointer_cast<Expression>(cp);
break;
case 2:
m_expNo = boost::dynamic_pointer_cast<Expression>(cp);
m_expNo = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
+5 -5
Ver Arquivo
@@ -15,7 +15,7 @@
*/
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/util/util.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/block_scope.h"
@@ -26,9 +26,9 @@
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/hash.h"
#include "hphp/runtime/base/string_data.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/string-data.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/ext/ext_variable.h"
#include "hphp/compiler/analysis/file_scope.h"
@@ -83,7 +83,7 @@ ScalarExpression::ScalarExpression
default:
assert(false);
}
CStrRef s = value.toString();
const String& s = value.toString();
m_value = string(s->data(), s->size());
if (m_type == T_DNUMBER && m_value.find_first_of(".eE", 0) == string::npos) {
m_value += ".";
+1 -1
Ver Arquivo
@@ -18,7 +18,7 @@
#define incl_HPHP_SCALAR_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+13 -11
Ver Arquivo
@@ -34,11 +34,12 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/externals.h"
#include "hphp/runtime/base/execution_context.h"
#include "hphp/runtime/base/array/array_init.h"
#include "hphp/runtime/base/string_util.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/base/zend-functions.h"
#include "hphp/runtime/ext/ext_variable.h"
using namespace HPHP;
@@ -205,7 +206,8 @@ void SimpleFunctionCall::mungeIfSpecialFunction(AnalysisResultConstPtr ar,
// making incorrect assumptions during WholeProgram mode. See
// AnalysisResult::collectFunctionsAndClasses.
case FunType::ClassAlias:
if ((m_params->getCount() == 2 || m_params->getCount() == 3) &&
if (m_params &&
(m_params->getCount() == 2 || m_params->getCount() == 3) &&
Option::WholeProgram) {
if (!(*m_params)[0]->isLiteralString() ||
!(*m_params)[1]->isLiteralString()) {
@@ -342,7 +344,7 @@ ConstructPtr SimpleFunctionCall::getNthKid(int n) const {
void SimpleFunctionCall::setNthKid(int n, ConstructPtr cp) {
if (n == 1) {
m_safeDef = boost::dynamic_pointer_cast<Expression>(cp);
m_safeDef = dynamic_pointer_cast<Expression>(cp);
} else {
FunctionCall::setNthKid(n, cp);
}
@@ -613,12 +615,12 @@ bool SimpleFunctionCall::isSimpleDefine(StringData **outName,
Variant v;
if (!(*m_params)[0]->getScalarValue(v) || !v.isString()) return false;
if (outName) {
*outName = StringData::GetStaticString(v.toCStrRef().get());
*outName = makeStaticString(v.toCStrRef().get());
}
if (!(*m_params)[1]->getScalarValue(v) || v.isArray()) return false;
if (outValue) {
if (v.isString()) {
v = StringData::GetStaticString(v.toCStrRef().get());
v = makeStaticString(v.toCStrRef().get());
}
*outValue = *v.asTypedValue();
}
@@ -737,10 +739,10 @@ ExpressionPtr SimpleFunctionCall::optimize(AnalysisResultConstPtr ar) {
name = voff.toString();
if (mode == EXTR_PREFIX_ALL ||
(mode == EXTR_PREFIX_INVALID &&
!name.isValidVariableName())) {
!is_valid_var_name(name.c_str(), name.size()))) {
name = prefix + "_" + name;
}
if (!name.isValidVariableName()) continue;
if (!is_valid_var_name(name.c_str(), name.size())) continue;
SimpleVariablePtr var(
new SimpleVariable(getScope(), getLocation(), name.data()));
var->updateSymbol(SimpleVariablePtr());
@@ -1230,7 +1232,7 @@ TypePtr SimpleFunctionCall::inferAndCheck(AnalysisResultPtr ar, TypePtr type,
Construct::recomputeEffects();
}
m_builtinFunction = (!func->isUserFunction() || func->isSepExtension());
m_builtinFunction = !func->isUserFunction();
beforeCheck(ar);
+8 -1
Ver Arquivo
@@ -42,7 +42,13 @@ public:
void setValid() { m_valid = true; }
void setFromCompiler() { m_fromCompiler = true; }
void setThrowFatal() { m_type = FunType::ThrowFatal; }
int isFatalFunction() const { return m_type == FunType::ThrowFatal; }
void setThrowParseFatal() { m_type = FunType::ThrowParseFatal; }
bool isParseFatalFunction() const {
return m_type == FunType::ThrowParseFatal;
}
bool isFatalFunction() const {
return isParseFatalFunction() || m_type == FunType::ThrowFatal;
}
int isStaticCompact() const { return m_type == FunType::StaticCompact; }
// define(<literal-string>, <scalar>);
@@ -93,6 +99,7 @@ protected:
GetDefinedVars,
FBCallUserFuncSafe,
ThrowFatal,
ThrowParseFatal,
ClassAlias,
};
+14 -19
Ver Arquivo
@@ -21,8 +21,8 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/util/parser/parser.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/parser/parser.h"
using namespace HPHP;
@@ -105,15 +105,6 @@ void SimpleVariable::coalesce(SimpleVariablePtr other) {
m_name = m_sym->getName();
}
string SimpleVariable::getNamePrefix() const {
bool needsCont = getFunctionScope()->isGenerator();
bool isHidden = m_sym && m_sym->isHidden();
return (needsCont &&
m_name != CONTINUATION_OBJECT_NAME &&
!isHidden) ?
string(TYPED_CONTINUATION_OBJECT_NAME) + "->" : string("");
}
/*
This simple variable is about to go out of scope.
Is it ok to kill the last assignment?
@@ -174,14 +165,18 @@ void SimpleVariable::analyzeProgram(AnalysisResultPtr ar) {
if (!m_sym->isSystem() &&
!(getContext() &
(LValue|RefValue|RefParameter|UnsetContext|ExistContext)) &&
m_sym->getDeclaration().get() == this &&
!variables->getAttribute(VariableTable::ContainsLDynamicVariable) &&
!getScope()->is(BlockScope::ClassScope)) {
if (getScope()->inPseudoMain()) {
Compiler::Error(Compiler::UseUndeclaredGlobalVariable,
shared_from_this());
} else if (!m_sym->isClosureVar()) {
Compiler::Error(Compiler::UseUndeclaredVariable, shared_from_this());
m_sym->getDeclaration().get() == this) {
assert(!m_sym->isParameter());
if (!variables->getAttribute(VariableTable::ContainsLDynamicVariable) &&
!getScope()->is(BlockScope::ClassScope)) {
if (getScope()->inPseudoMain()) {
Compiler::Error(Compiler::UseUndeclaredGlobalVariable,
shared_from_this());
} else if (!m_sym->isClosureVar()) {
Compiler::Error(Compiler::UseUndeclaredVariable,
shared_from_this());
}
}
}
// check function parameter that can occur in lval context
-2
Ver Arquivo
@@ -59,8 +59,6 @@ public:
void updateSymbol(SimpleVariablePtr src);
void coalesce(SimpleVariablePtr other);
private:
std::string getNamePrefix() const;
std::string m_name;
std::string m_docComment;
@@ -24,7 +24,7 @@
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/option.h"
using namespace HPHP;
@@ -137,10 +137,10 @@ int StaticMemberExpression::getKidCount() const {
void StaticMemberExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_class = boost::dynamic_pointer_cast<Expression>(cp);
m_class = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_exp = boost::dynamic_pointer_cast<Expression>(cp);
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
+22 -13
Ver Arquivo
@@ -16,7 +16,7 @@
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/statement/statement_list.h"
@@ -29,8 +29,8 @@
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/expression/encaps_list_expression.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/compiler/parser/parser.h"
using namespace HPHP;
@@ -237,21 +237,30 @@ bool UnaryOpExpression::preCompute(CVarRef value, Variant &result) {
*result.asCell());
break;
case '~':
result = value.bitNot(); break;
tvSet(*value.asCell(), *result.asTypedValue());
cellBitNot(*result.asCell());
break;
case '@':
result = value; break;
result = value;
break;
case T_INT_CAST:
result = value.toInt64(); break;
result = value.toInt64();
break;
case T_DOUBLE_CAST:
result = toDouble(value); break;
result = toDouble(value);
break;
case T_STRING_CAST:
result = toString(value); break;
result = toString(value);
break;
case T_BOOL_CAST:
result = toBoolean(value); break;
result = toBoolean(value);
break;
case T_EMPTY:
result = empty(value); break;
result = !toBoolean(value);
break;
case T_ISSET:
result = isset(value); break;
result = is_not_null(value);
break;
case T_INC:
case T_DEC:
assert(false);
@@ -284,7 +293,7 @@ int UnaryOpExpression::getKidCount() const {
void UnaryOpExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = boost::dynamic_pointer_cast<Expression>(cp);
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -326,7 +335,7 @@ ExpressionPtr UnaryOpExpression::preOptimize(AnalysisResultConstPtr ar) {
for (; i < n; i++) {
ExpressionPtr e((*el)[i]);
if (!e || !e->isScalar() || !e->getScalarValue(value)) break;
if (!isset(value)) {
if (value.isNull()) {
result = false;
}
}
+1 -1
Ver Arquivo
@@ -18,7 +18,7 @@
#define incl_HPHP_UNARY_OP_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+7 -7
Ver Arquivo
@@ -26,7 +26,7 @@ YieldExpression::YieldExpression
(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr keyExp, ExpressionPtr valExp)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(YieldExpression)),
m_keyExp(keyExp), m_valExp(valExp), m_label(-1) {
m_keyExp(keyExp), m_valExp(valExp), m_label(this) {
}
ExpressionPtr YieldExpression::clone() {
@@ -34,7 +34,7 @@ ExpressionPtr YieldExpression::clone() {
Expression::deepCopy(exp);
exp->m_keyExp = Clone(m_keyExp);
exp->m_valExp = Clone(m_valExp);
exp->m_label = m_label;
exp->m_label.setExpression(exp.get());
return exp;
}
@@ -50,10 +50,10 @@ void YieldExpression::analyzeProgram(AnalysisResultPtr ar) {
if (m_keyExp) {
m_keyExp->analyzeProgram(ar);
}
m_valExp->setChildOfYield();
m_valExp->analyzeProgram(ar);
if (m_label == -1) {
setLabel(getFunctionScope()->allocYieldLabel());
}
m_label.setNew();
}
ConstructPtr YieldExpression::getNthKid(int n) const {
@@ -76,10 +76,10 @@ int YieldExpression::getKidCount() const {
void YieldExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_keyExp = boost::dynamic_pointer_cast<Expression>(cp);
m_keyExp = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_valExp = boost::dynamic_pointer_cast<Expression>(cp);
m_valExp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
+3 -3
Ver Arquivo
@@ -18,6 +18,7 @@
#define incl_HPHP_YIELD_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/generation_label.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -33,13 +34,12 @@ public:
ExpressionPtr getKeyExpression() { return m_keyExp; }
ExpressionPtr getValueExpression() { return m_valExp; }
int getLabel() { assert(m_label >= 1); return m_label; }
void setLabel(int label) { assert(m_label == -1); m_label = label; }
GenerationLabel& label() { return m_label; }
private:
ExpressionPtr m_keyExp;
ExpressionPtr m_valExp;
int m_label;
GenerationLabel m_label;
};
///////////////////////////////////////////////////////////////////////////////
+1 -1
Ver Arquivo
@@ -18,7 +18,7 @@
#define incl_HPHP_H_
#include "hphp/util/base.h"
#include "hphp/util/case_insensitive.h"
#include "hphp/util/case-insensitive.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+19 -25
Ver Arquivo
@@ -19,9 +19,9 @@
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/util/parser/scanner.h"
#include "hphp/parser/scanner.h"
#include "hphp/util/logger.h"
#include "hphp/util/db_query.h"
#include "hphp/util/db-query.h"
#include "hphp/util/util.h"
#include "hphp/util/process.h"
#include <boost/algorithm/string/trim.hpp>
@@ -53,7 +53,6 @@ map<string, string> Option::IncludeRoots;
map<string, string> Option::AutoloadRoots;
vector<string> Option::IncludeSearchPaths;
string Option::DefaultIncludeRoot;
vector<Option::SepExtensionOptions> Option::SepExtensions;
map<string, int> Option::DynamicFunctionCalls;
bool Option::GeneratePickledPHP = false;
@@ -113,19 +112,21 @@ std::string Option::ProgramName;
bool Option::ParseTimeOpts = true;
bool Option::EnableHipHopSyntax = false;
bool Option::EnableZendCompat = false;
bool Option::JitEnableRenameFunction = false;
bool Option::EnableHipHopExperimentalSyntax = false;
bool Option::EnableShortTags = true;
bool Option::EnableAspTags = false;
bool Option::EnableXHP = true;
bool Option::EnableXHP = false;
bool Option::EnableFinallyStatement = false;
int Option::ParserThreadCount = 0;
int Option::GetScannerType() {
int type = 0;
if (EnableShortTags) type |= Scanner::AllowShortTags;
if (EnableHipHopSyntax) type |= Scanner::AllowHipHopSyntax;
if (EnableAspTags) type |= Scanner::AllowAspTags;
if (EnableXHP) type |= Scanner::AllowXHPSyntax;
if (EnableHipHopSyntax) type |= Scanner::AllowHipHopSyntax;
return type;
}
@@ -226,23 +227,6 @@ void Option::Load(Hdf &config) {
READ_CG_OPTION(LambdaPrefix);
}
int count = 0;
for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists();
hdf = hdf.next()) {
++count;
}
SepExtensions.resize(count);
count = 0;
for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists();
hdf = hdf.next()) {
SepExtensionOptions &options = SepExtensions[count++];
options.name = hdf.getName();
options.soname = hdf["soname"].getString();
options.include_path = hdf["include"].getString();
options.lib_path = hdf["libpath"].getString();
options.shared = hdf["shared"].getBool();
}
config["DynamicFunctionPrefix"].get(DynamicFunctionPrefixes);
config["DynamicFunctionPostfix"].get(DynamicFunctionPostfixes);
config["DynamicMethodPrefix"].get(DynamicMethodPrefixes);
@@ -278,6 +262,7 @@ void Option::Load(Hdf &config) {
HardTypeHints = config["HardTypeHints"].getBool(true);
EnableHipHopSyntax = config["EnableHipHopSyntax"].getBool();
EnableZendCompat = config["EnableZendCompat"].getBool();
JitEnableRenameFunction = config["JitEnableRenameFunction"].getBool();
EnableHipHopExperimentalSyntax =
config["EnableHipHopExperimentalSyntax"].getBool();
@@ -285,7 +270,13 @@ void Option::Load(Hdf &config) {
EnableAspTags = config["EnableAspTags"].getBool();
EnableXHP = config["EnableXHP"].getBool(true);
EnableXHP = config["EnableXHP"].getBool(false);
if (EnableHipHopSyntax) {
// If EnableHipHopSyntax is true, it forces EnableXHP to true
// regardless of how it was set in the config
EnableXHP = true;
}
ParserThreadCount = config["ParserThreadCount"].getInt32(0);
if (ParserThreadCount <= 0) {
@@ -313,6 +304,9 @@ void Option::Load(Hdf &config) {
DumpAst = config["DumpAst"].getBool(false);
WholeProgram = config["WholeProgram"].getBool(true);
// Temporary, during file-cache migration.
FileCache::UseNewCache = config["UseNewCache"].getBool(false);
if (m_hookHandler) m_hookHandler(config);
OnLoad();
@@ -387,13 +381,13 @@ std::string Option::MangleFilename(const std::string &name, bool id) {
bool Option::IsFileExcluded(const std::string &file,
const std::set<std::string> &patterns) {
String sfile(file.c_str(), file.size(), AttachLiteral);
String sfile(file.c_str(), file.size(), CopyString);
for (set<string>::const_iterator iter = patterns.begin();
iter != patterns.end(); ++iter) {
const std::string &pattern = *iter;
Variant matches;
Variant ret = preg_match(String(pattern.c_str(), pattern.size(),
AttachLiteral), sfile, matches);
CopyString), sfile, matches);
if (ret.toInt64() > 0) {
return true;
}
+2 -13
Ver Arquivo
@@ -18,7 +18,7 @@
#define incl_HPHP_OPTION_H_
#include "hphp/util/hdf.h"
#include "hphp/util/string_bag.h"
#include "hphp/util/string-bag.h"
#include "hphp/util/base.h"
namespace HPHP {
@@ -100,18 +100,6 @@ public:
*/
static std::map<std::string, int> DynamicFunctionCalls;
/**
* Separable extensions that are loaded dynamically.
*/
struct SepExtensionOptions {
std::string name;
std::string soname;
std::string include_path;
std::string lib_path;
bool shared;
};
static std::vector<SepExtensionOptions> SepExtensions;
/**
* Optimization flags
*/
@@ -228,6 +216,7 @@ public:
static bool ParseTimeOpts;
static bool OutputHHBC;
static bool EnableHipHopSyntax;
static bool EnableZendCompat;
static bool JitEnableRenameFunction;
static bool EnableHipHopExperimentalSyntax;
static bool EnableShortTags;
+6 -5
Ver Arquivo
@@ -19,6 +19,7 @@
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include "folly/String.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/analysis/symbol_table.h"
@@ -28,11 +29,11 @@
#include "hphp/util/util.h"
#include "hphp/util/logger.h"
#include "hphp/util/json.h"
#include "hphp/util/db_conn.h"
#include "hphp/util/db_query.h"
#include "hphp/util/db-conn.h"
#include "hphp/util/db-query.h"
#include "hphp/util/exception.h"
#include "hphp/util/job_queue.h"
#include "hphp/runtime/base/execution_context.h"
#include "hphp/util/job-queue.h"
#include "hphp/runtime/base/execution-context.h"
using namespace HPHP;
using std::set;
@@ -67,7 +68,7 @@ void Package::addInputList(const char *listFileName) {
FILE *f = fopen(listFileName, "r");
if (f == nullptr) {
throw Exception("Unable to open %s: %s", listFileName,
Util::safe_strerror(errno).c_str());
folly::errnoStr(errno).c_str());
}
char fileName[PATH_MAX];
while (fgets(fileName, sizeof(fileName), f)) {
+2 -2
Ver Arquivo
@@ -18,8 +18,8 @@
#define incl_HPHP_PACKAGE_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/string_bag.h"
#include "hphp/util/file_cache.h"
#include "hphp/util/string-bag.h"
#include "hphp/util/file-cache.h"
#include "hphp/util/mutex.h"
namespace HPHP {
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+319 -326
Ver Arquivo
@@ -15,10 +15,8 @@
*/
#include "hphp/compiler/parser/parser.h"
#include <boost/make_shared.hpp>
#include "hphp/compiler/type_annotation.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/expression_list.h"
@@ -46,6 +44,7 @@
#include "hphp/compiler/expression/encaps_list_expression.h"
#include "hphp/compiler/expression/closure_expression.h"
#include "hphp/compiler/expression/yield_expression.h"
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/compiler/statement/function_statement.h"
@@ -91,7 +90,7 @@
#include "hphp/util/lock.h"
#include "hphp/util/logger.h"
#include "hphp/runtime/base/file_repository.h"
#include "hphp/runtime/base/file-repository.h"
#ifdef FACEBOOK
#include "hphp/facebook/src/compiler/fb_compiler_hooks.h"
@@ -113,13 +112,6 @@
using namespace HPHP::Compiler;
extern void prepare_generator(Parser *_p, Token &stmt, Token &params);
extern void create_generator(Parser *_p, Token &out, Token &params,
Token &name, const std::string &genName,
const char *clsname, Token *modifiers,
Token &origGenFunc, bool isHhvm,
Token *attr);
namespace HPHP {
SimpleFunctionCallPtr NewSimpleFunctionCall(
@@ -136,7 +128,7 @@ namespace Compiler {
///////////////////////////////////////////////////////////////////////////////
// statics
StatementListPtr Parser::ParseString(CStrRef input, AnalysisResultPtr ar,
StatementListPtr Parser::ParseString(const String& input, AnalysisResultPtr ar,
const char *fileName /* = NULL */,
bool lambdaMode /* = false */) {
assert(!input.empty());
@@ -182,10 +174,16 @@ bool Parser::parse() {
"Parse error: %s",
errString().c_str());
}
} catch (ParseTimeFatalException &e) {
m_file->cleanupForError(m_ar, e.m_line, e.getMessage());
return true;
} catch (const ParseTimeFatalException& e) {
m_file->cleanupForError(m_ar);
if (e.m_parseFatal) {
m_file->makeParseFatal(m_ar, e.getMessage(), e.m_line);
} else {
m_file->makeFatal(m_ar, e.getMessage(), e.m_line);
}
return false;
}
return true;
}
void Parser::error(const char* fmt, ...) {
@@ -198,19 +196,22 @@ void Parser::error(const char* fmt, ...) {
fatal(&m_loc, msg.c_str());
}
void Parser::fatal(Location *loc, const char *msg) {
throw ParseTimeFatalException(loc->file, loc->line0,
"%s", msg);
void Parser::parseFatal(const Location* loc, const char* msg) {
// we can't use loc->file, as the bison parser doesn't track that in YYLTYPE
auto file = m_file->getName().c_str();
auto exn = ParseTimeFatalException(file, loc->line0, "%s", msg);
exn.setParseFatal();
throw exn;
}
void Parser::fatal(const Location* loc, const char* msg) {
throw ParseTimeFatalException(loc->file, loc->line0, "%s", msg);
}
string Parser::errString() {
return m_error.empty() ? getMessage() : m_error;
}
bool Parser::enableXHP() {
return Option::EnableXHP;
}
bool Parser::enableFinallyStatement() {
return Option::EnableFinallyStatement;
}
@@ -652,7 +653,6 @@ void Parser::onUnaryOpExp(Token &out, Token &operand, int op, bool front) {
case T_INC:
case T_DEC:
case T_ISSET:
case T_EMPTY:
case T_UNSET:
if (dynamic_pointer_cast<FunctionCall>(operand->exp)) {
PARSE_ERROR("Can't use return value in write context");
@@ -691,7 +691,7 @@ void Parser::onQOp(Token &out, Token &exprCond, Token *expYes, Token &expNo) {
}
void Parser::onArray(Token &out, Token &pairs, int op /* = T_ARRAY */) {
if (op != T_ARRAY && !m_scanner.hipHopSyntaxEnabled()) {
if (op != T_ARRAY && !m_scanner.isHHSyntaxEnabled()) {
PARSE_ERROR("Typed collection is not enabled");
return;
}
@@ -805,111 +805,184 @@ void Parser::fixStaticVars() {
m_staticVars.pop_back();
}
void Parser::onFunction(Token &out, Token *modifiers, Token &ret, Token &ref,
Token &name, Token &params, Token &stmt, Token *attr) {
ModifierExpressionPtr exp = modifiers?
void Parser::checkFunctionContext(string funcName,
FunctionContext& funcContext,
ModifierExpressionPtr modifiers,
int returnsRef) {
funcContext.checkFinalAssertions();
// let async modifier be mandatory
if (funcContext.isAsync && !modifiers->isAsync()) {
PARSE_ERROR("Function '%s' contains 'await' but is not declared as async.",
funcName.c_str());
}
if (modifiers->isAsync() && returnsRef) {
PARSE_ERROR("Asynchronous function '%s' cannot return reference.",
funcName.c_str());
}
if (modifiers->isAsync() && funcContext.isGenerator) {
PARSE_ERROR("'yield' is not allowed in async functions.");
}
}
void Parser::prepareConstructorParameters(StatementListPtr stmts,
ExpressionListPtr params,
bool isAbstract) {
for (int i = 0, count = params->getCount(); i < count; i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*params)[i]);
TokenID mod = param->getModifier();
if (mod == 0) continue;
if (isAbstract) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not allowed on "
"abstract __construct");
}
if (!stmts) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not allowed on "
"__construct without a body");
}
if (param->annotation()) {
std::vector<std::string> typeNames;
param->annotation()->getAllSimpleNames(typeNames);
for (auto& typeName : typeNames) {
if (isTypeVarInImmediateScope(typeName)) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not supported with "
"type variable annotation");
}
}
}
std::string name = param->getName();
SimpleVariablePtr value = NEW_EXP(SimpleVariable, name);
ScalarExpressionPtr prop = NEW_EXP(ScalarExpression, T_STRING, name);
SimpleVariablePtr self = NEW_EXP(SimpleVariable, "this");
ObjectPropertyExpressionPtr objProp =
NEW_EXP(ObjectPropertyExpression, self, prop);
AssignmentExpressionPtr assign =
NEW_EXP(AssignmentExpression, objProp, value, false);
ExpStatementPtr stmt = NEW_STMT(ExpStatement, assign);
stmts->insertElement(stmt);
}
}
string Parser::getFunctionName(FunctionType type, Token* name) {
switch (type) {
case FunctionType::Closure:
return newClosureName(m_clsName, m_containingFuncName);
case FunctionType::Function:
assert(name);
if (!m_lambdaMode) {
return name->text();
} else {
return name->text() + "{lambda}";
}
case FunctionType::Method:
assert(name);
return name->text();
}
not_reached();
}
StatementPtr Parser::onFunctionHelper(FunctionType type,
Token *modifiers, Token &ret,
Token &ref, Token *name, Token &params,
Token &stmt, Token *attr, bool reloc) {
// prepare and validate function modifiers
ModifierExpressionPtr modifiersExp = modifiers && modifiers->exp ?
dynamic_pointer_cast<ModifierExpression>(modifiers->exp)
: NEW_EXP0(ModifierExpression);
if (!stmt->stmt) {
stmt->stmt = NEW_STMT0(StatementList);
modifiersExp->setHasPrivacy(type == FunctionType::Method);
if (type == FunctionType::Closure && !modifiersExp->validForClosure()) {
PARSE_ERROR("Invalid modifier on closure funciton.");
}
if (type == FunctionType::Function && !modifiersExp->validForFunction()) {
PARSE_ERROR("Invalid modifier on function %s.", name->text().c_str());
}
StatementListPtr stmts = stmt->stmt || stmt->num() != 1 ?
dynamic_pointer_cast<StatementList>(stmt->stmt)
: NEW_EXP0(StatementList);
ExpressionListPtr old_params =
dynamic_pointer_cast<ExpressionList>(params->exp);
int attribute = m_file->popAttribute();
string comment = popComment();
LocationPtr loc = popFuncLocation();
FunctionContext funcContext = m_funcContexts.back();
m_funcContexts.pop_back();
m_prependingStatements.pop_back();
string funcName = getFunctionName(type, name);
funcContext.checkFinalAssertions();
bool hasCallToGetArgs = m_hasCallToGetArgs.back();
m_hasCallToGetArgs.pop_back();
if (type == FunctionType::Method && old_params &&
funcName == "__construct") {
prepareConstructorParameters(stmts, old_params,
modifiersExp->isAbstract());
}
fixStaticVars();
int attribute = m_file->popAttribute();
string comment = popComment();
ExpressionListPtr attrList;
if (attr && attr->exp) {
attrList = dynamic_pointer_cast<ExpressionList>(attr->exp);
}
// create function/method statement
FunctionStatementPtr func;
string funcName = name->text();
if (funcName.empty()) {
funcName = newClosureName(m_clsName, m_containingFuncName);
} else if (m_lambdaMode) {
funcName += "{lambda}";
}
if (funcContext.isGenerator) {
string genName = newContinuationName(funcName);
Token new_params;
prepare_generator(this, stmt, new_params);
func = NEW_STMT(FunctionStatement, exp, ref->num(), genName,
dynamic_pointer_cast<ExpressionList>(new_params->exp),
ret.typeAnnotationName(),
dynamic_pointer_cast<StatementList>(stmt->stmt),
attribute, comment, ExpressionListPtr());
out->stmt = func;
func->getLocation()->line0 = loc->line0;
func->getLocation()->char0 = loc->char0;
{
func->onParse(m_ar, m_file);
}
completeScope(func->getFunctionScope());
if (func->ignored()) {
out->stmt = NEW_STMT0(StatementList);
} else {
assert(!m_prependingStatements.empty());
vector<StatementPtr> &prepending = m_prependingStatements.back();
prepending.push_back(func);
if (name->text().empty()) m_closureGenerator = true;
// create_generator() expects us to push the docComment back
// onto the comment stack so that it can make sure that the
// the MethodStatement it's building will get the docComment
pushComment(comment);
Token origGenFunc;
create_generator(this, out, params, name, genName, nullptr, nullptr,
origGenFunc,
(!Option::WholeProgram || !Option::ParseTimeOpts),
attr);
m_closureGenerator = false;
MethodStatementPtr origStmt =
boost::dynamic_pointer_cast<MethodStatement>(origGenFunc->stmt);
assert(origStmt);
func->setOrigGeneratorFunc(origStmt);
origStmt->setGeneratorFunc(func);
origStmt->setHasCallToGetArgs(hasCallToGetArgs);
}
MethodStatementPtr mth;
if (type == FunctionType::Method) {
mth = NEW_STMT(MethodStatement, modifiersExp,
ref->num(), funcName, old_params,
ret.typeAnnotation, stmts,
attribute, comment, attrList);
completeScope(mth->onInitialParse(m_ar, m_file));
} else {
ExpressionListPtr attrList;
if (attr && attr->exp) {
attrList = dynamic_pointer_cast<ExpressionList>(attr->exp);
}
func = NEW_STMT(FunctionStatement, modifiersExp,
ref->num(), funcName, old_params,
ret.typeAnnotation, stmts,
attribute, comment, attrList);
func = NEW_STMT(FunctionStatement, exp, ref->num(), funcName, old_params,
ret.typeAnnotationName(),
dynamic_pointer_cast<StatementList>(stmt->stmt),
attribute, comment, attrList);
out->stmt = func;
{
func->onParse(m_ar, m_file);
}
func->onParse(m_ar, m_file);
completeScope(func->getFunctionScope());
if (m_closureGenerator) {
func->getFunctionScope()->setClosureGenerator();
}
func->getLocation()->line0 = loc->line0;
func->getLocation()->char0 = loc->char0;
if (func->ignored()) {
out->stmt = NEW_STMT0(StatementList);
return NEW_STMT0(StatementList);
}
mth = func;
}
func->setHasCallToGetArgs(hasCallToGetArgs);
// check and set generator/async flags
FunctionContext funcContext = m_funcContexts.back();
checkFunctionContext(funcName, funcContext, modifiersExp, ref->num());
mth->getFunctionScope()->setGenerator(funcContext.isGenerator);
mth->getFunctionScope()->setAsync(modifiersExp->isAsync());
m_funcContexts.pop_back();
mth->setHasCallToGetArgs(m_hasCallToGetArgs.back());
m_hasCallToGetArgs.pop_back();
LocationPtr loc = popFuncLocation();
if (reloc) {
mth->getLocation()->line0 = loc->line0;
mth->getLocation()->char0 = loc->char0;
}
m_prependingStatements.pop_back();
return mth;
}
void Parser::onFunction(Token &out, Token *modifiers, Token &ret, Token &ref,
Token &name, Token &params, Token &stmt, Token *attr) {
out->stmt = onFunctionHelper(FunctionType::Function,
modifiers, ret, ref, &name, params, stmt, attr, true);
}
void Parser::onMethod(Token &out, Token &modifiers, Token &ret, Token &ref,
Token &name, Token &params, Token &stmt,
Token *attr, bool reloc /* = true */) {
out->stmt = onFunctionHelper(FunctionType::Method,
&modifiers, ret, ref, &name, params, stmt, attr, reloc);
}
void Parser::onParam(Token &out, Token *params, Token &type, Token &var,
@@ -927,7 +1000,7 @@ void Parser::onParam(Token &out, Token *params, Token &type, Token &var,
TypeAnnotationPtr typeAnnotation = type.typeAnnotation;
expList->addElement(NEW_EXP(ParameterExpression, typeAnnotation,
m_scanner.hipHopSyntaxEnabled(), var->text(),
m_scanner.isHHSyntaxEnabled(), var->text(),
ref, (modifier) ? modifier->num() : 0,
defValue ? defValue->exp : ExpressionPtr(),
attrList));
@@ -936,7 +1009,7 @@ void Parser::onParam(Token &out, Token *params, Token &type, Token &var,
void Parser::onClassStart(int type, Token &name) {
const Type::TypePtrMap& typeHintTypes =
Type::GetTypeHintTypes(m_scanner.hipHopSyntaxEnabled());
Type::GetTypeHintTypes(m_scanner.isHHSyntaxEnabled());
if (name.text() == "self" || name.text() == "parent" ||
typeHintTypes.find(name.text()) != typeHintTypes.end()) {
PARSE_ERROR("Cannot use '%s' as class name as it is reserved",
@@ -1136,146 +1209,6 @@ void Parser::onClassVariableStart(Token &out, Token *modifiers, Token &decl,
}
}
void Parser::onMethod(Token &out, Token &modifiers, Token &ret, Token &ref,
Token &name, Token &params, Token &stmt,
Token *attr, bool reloc /* = true */) {
ModifierExpressionPtr exp = modifiers->exp ?
dynamic_pointer_cast<ModifierExpression>(modifiers->exp)
: NEW_EXP0(ModifierExpression);
StatementListPtr stmts;
if (!stmt->stmt && stmt->num() == 1) {
stmts = NEW_STMT0(StatementList);
} else {
stmts = dynamic_pointer_cast<StatementList>(stmt->stmt);
}
ExpressionListPtr old_params =
dynamic_pointer_cast<ExpressionList>(params->exp);
// look for argument promotion in ctor and add to function body
string funcName = name->text();
if (old_params && funcName == "__construct") {
bool isAbstract = (exp) ? exp->isAbstract() : false;
for (int i = 0, count = old_params->getCount(); i < count; i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*old_params)[i]);
TokenID mod = param->getModifier();
if (mod != 0) {
if (isAbstract) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not allowed on "
"abstract __construct");
}
if (!stmts) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not allowed on "
"__construct without a body");
}
if (param->annotation()) {
std::vector<std::string> typeNames;
param->annotation()->getAllSimpleNames(typeNames);
for (auto& typeName : typeNames) {
if (isTypeVarInImmediateScope(typeName)) {
param->parseTimeFatal(Compiler::InvalidAttribute,
"parameter modifiers not supported with "
"type variable annotation");
}
}
}
std::string name = param->getName();
SimpleVariablePtr value = NEW_EXP(SimpleVariable, name);
ScalarExpressionPtr prop = NEW_EXP(ScalarExpression, T_STRING, name);
SimpleVariablePtr self = NEW_EXP(SimpleVariable, "this");
ObjectPropertyExpressionPtr objProp =
NEW_EXP(ObjectPropertyExpression, self, prop);
AssignmentExpressionPtr assign =
NEW_EXP(AssignmentExpression, objProp, value, false);
ExpStatementPtr stmt = NEW_STMT(ExpStatement, assign);
stmts->insertElement(stmt);
}
}
}
int attribute = m_file->popAttribute();
string comment = popComment();
LocationPtr loc = popFuncLocation();
FunctionContext funcContext = m_funcContexts.back();
m_funcContexts.pop_back();
m_prependingStatements.pop_back();
funcContext.checkFinalAssertions();
bool hasCallToGetArgs = m_hasCallToGetArgs.back();
m_hasCallToGetArgs.pop_back();
fixStaticVars();
MethodStatementPtr mth;
if (funcName.empty()) {
funcName = newClosureName(m_clsName, m_containingFuncName);
}
if (funcContext.isGenerator) {
string genName = newContinuationName(funcName);
if (m_inTrait) {
// see traits/2067.php
genName = newContinuationName(funcName + "@" + m_clsName);
}
Token new_params;
prepare_generator(this, stmt, new_params);
ModifierExpressionPtr exp2 = Construct::Clone(exp);
mth = NEW_STMT(MethodStatement, exp2, ref->num(), genName,
dynamic_pointer_cast<ExpressionList>(new_params->exp),
ret.typeAnnotationName(),
dynamic_pointer_cast<StatementList>(stmt->stmt),
attribute, comment, ExpressionListPtr());
out->stmt = mth;
if (reloc) {
mth->getLocation()->line0 = loc->line0;
mth->getLocation()->char0 = loc->char0;
}
{
completeScope(mth->onInitialParse(m_ar, m_file));
}
// create_generator() expects us to push the docComment back
// onto the comment stack so that it can make sure that the
// the MethodStatement it's building will get the docComment
pushComment(comment);
Token origGenFunc;
create_generator(this, out, params, name, genName, m_clsName.c_str(),
&modifiers, origGenFunc,
(!Option::WholeProgram || !Option::ParseTimeOpts),
attr);
MethodStatementPtr origStmt =
boost::dynamic_pointer_cast<MethodStatement>(origGenFunc->stmt);
assert(origStmt);
mth->setOrigGeneratorFunc(origStmt);
origStmt->setGeneratorFunc(mth);
origStmt->setHasCallToGetArgs(hasCallToGetArgs);
} else {
ExpressionListPtr attrList;
if (attr && attr->exp) {
attrList = dynamic_pointer_cast<ExpressionList>(attr->exp);
}
mth = NEW_STMT(MethodStatement, exp, ref->num(), funcName,
old_params,
ret.typeAnnotationName(),
stmts, attribute, comment,
attrList);
out->stmt = mth;
if (reloc) {
mth->getLocation()->line0 = loc->line0;
mth->getLocation()->char0 = loc->char0;
}
completeScope(mth->onInitialParse(m_ar, m_file));
}
mth->setHasCallToGetArgs(hasCallToGetArgs);
}
void Parser::onMemberModifier(Token &out, Token *modifiers, Token &modifier) {
ModifierExpressionPtr expList;
if (modifiers) {
@@ -1445,112 +1378,163 @@ void Parser::onCase(Token &out, Token &cases, Token *cond, Token &stmt) {
stmt->stmt));
}
void Parser::onBreak(Token &out, Token *expr) {
if (expr) {
int64_t depth = strtoll(expr->text().c_str(), nullptr, 0);
if (depth <= 0) {
PARSE_ERROR("'break' operator accepts only positive numbers");
}
out->stmt = NEW_STMT(BreakStatement, static_cast<uint64_t>(depth));
} else {
out->stmt = NEW_STMT(BreakStatement, 1UL);
}
}
void Parser::onBreakContinue(Token &out, bool isBreak, Token* expr) {
uint64_t depth = 1;
void Parser::onContinue(Token &out, Token *expr) {
if (expr) {
int64_t depth = strtoll(expr->text().c_str(), nullptr, 0);
if (depth <= 0) {
PARSE_ERROR("'continue' operator accepts only positive numbers");
Variant v;
if (!expr->exp->getScalarValue(v)) {
PARSE_ERROR("'%s' operator with non-constant operand is no longer "
"supported", (isBreak ? "break" : "continue"));
}
out->stmt = NEW_STMT(ContinueStatement, static_cast<uint64_t>(depth));
if (!v.isInteger() || v.toInt64() <= 0) {
PARSE_ERROR("'%s' operator accepts only positive numbers",
(isBreak ? "break" : "continue"));
}
depth = static_cast<uint64_t>(v.toInt64());
}
if (isBreak) {
out->stmt = NEW_STMT(BreakStatement, depth);
} else {
out->stmt = NEW_STMT(ContinueStatement, 1UL);
out->stmt = NEW_STMT(ContinueStatement, depth);
}
}
void Parser::onReturn(Token &out, Token *expr) {
out->stmt = NEW_STMT(ReturnStatement, expr ? expr->exp : ExpressionPtr());
if (!m_funcContexts.empty()) {
if (!m_funcContexts.back().setIsNotGenerator()) {
FunctionContext& fc = m_funcContexts.back();
if (fc.isGenerator) {
Compiler::Error(InvalidYield, out->stmt);
PARSE_ERROR("Cannot mix 'return' and 'yield' in the same function");
return;
}
fc.hasReturn = true;
}
}
static void invalidYield(LocationPtr loc) {
ExpressionPtr exp(new SimpleFunctionCall(BlockScopePtr(), loc, "yield",
void Parser::invalidYield() {
ExpressionPtr exp(new SimpleFunctionCall(BlockScopePtr(),
getLocation(),
"yield",
false,
ExpressionListPtr(),
ExpressionPtr()));
Compiler::Error(Compiler::InvalidYield, exp);
}
bool Parser::canBeAsyncOrGenerator(string funcName, string clsName) {
if (clsName.empty()) {
return true;
}
if (strcasecmp(funcName.c_str(), clsName.c_str()) == 0) {
return false;
}
if (strncmp(funcName.c_str(), "__", 2) == 0) {
const char *fname = funcName.c_str() + 2;
if (!strcasecmp(fname, "construct") ||
!strcasecmp(fname, "destruct") ||
!strcasecmp(fname, "get") ||
!strcasecmp(fname, "set") ||
!strcasecmp(fname, "isset") ||
!strcasecmp(fname, "unset") ||
!strcasecmp(fname, "call") ||
!strcasecmp(fname, "callstatic") ||
!strcasecmp(fname, "invoke")) {
return false;
}
}
return true;
}
bool Parser::setIsGenerator() {
if (m_funcContexts.empty()) {
invalidYield(getLocation());
invalidYield();
PARSE_ERROR("Yield can only be used inside a function");
return false;
}
if (!m_funcContexts.back().setIsGenerator()) {
invalidYield(getLocation());
FunctionContext& fc = m_funcContexts.back();
if (fc.hasReturn) {
invalidYield();
PARSE_ERROR("Cannot mix 'return' and 'yield' in the same function");
return false;
}
if (fc.isAsync) {
invalidYield();
PARSE_ERROR("'yield' is not allowed in async functions.");
return false;
}
fc.isGenerator = true;
if (!m_clsName.empty()) {
if (strcasecmp(m_funcName.c_str(), m_clsName.c_str()) == 0) {
invalidYield(getLocation());
PARSE_ERROR("'yield' is not allowed in potential constructors");
return false;
}
if (m_funcName[0] == '_' && m_funcName[1] == '_') {
const char *fname = m_funcName.c_str() + 2;
if (!strcasecmp(fname, "construct") ||
!strcasecmp(fname, "destruct") ||
!strcasecmp(fname, "get") ||
!strcasecmp(fname, "set") ||
!strcasecmp(fname, "isset") ||
!strcasecmp(fname, "unset") ||
!strcasecmp(fname, "call") ||
!strcasecmp(fname, "callstatic") ||
!strcasecmp(fname, "invoke")) {
invalidYield(getLocation());
PARSE_ERROR("'yield' is not allowed in constructor, destructor, or "
"magic methods");
return false;
}
}
if (!canBeAsyncOrGenerator(m_funcName, m_clsName)) {
invalidYield();
PARSE_ERROR("'yield' is not allowed in constructor, destructor, or "
"magic methods");
return false;
}
return true;
}
void Parser::onYield(Token &out, Token &expr) {
if (!setIsGenerator()) {
return;
if (setIsGenerator()) {
out->exp = NEW_EXP(YieldExpression, ExpressionPtr(), expr->exp);
}
out->exp = NEW_EXP(YieldExpression, ExpressionPtr(), expr->exp);
}
void Parser::onYieldPair(Token &out, Token &key, Token &val) {
if (!setIsGenerator()) {
return;
if (setIsGenerator()) {
out->exp = NEW_EXP(YieldExpression, key->exp, val->exp);
}
out->exp = NEW_EXP(YieldExpression, key->exp, val->exp);
}
void Parser::onYieldBreak(Token &out) {
if (!setIsGenerator()) {
return;
if (setIsGenerator()) {
out->stmt = NEW_STMT(ReturnStatement, ExpressionPtr());
}
}
void Parser::invalidAwait() {
ExpressionPtr exp(new SimpleFunctionCall(BlockScopePtr(),
getLocation(),
"async",
false,
ExpressionListPtr(),
ExpressionPtr()));
Compiler::Error(Compiler::InvalidAwait, exp);
}
bool Parser::setIsAsync() {
if (m_funcContexts.empty()) {
invalidAwait();
PARSE_ERROR("'await' can only be used inside a function");
return false;
}
out->stmt = NEW_STMT(ReturnStatement, ExpressionPtr());
FunctionContext& fc = m_funcContexts.back();
if (fc.isGenerator) {
invalidAwait();
PARSE_ERROR("'await' is not allowed in generators.");
return false;
}
fc.isAsync = true;
if (!canBeAsyncOrGenerator(m_funcName, m_clsName)) {
invalidAwait();
PARSE_ERROR("'await' is not allowed in constructors, destructors, or "
"magic methods.");
}
return true;
}
void Parser::onAwait(Token &out, Token &expr) {
if (setIsAsync()) {
out->exp = NEW_EXP(AwaitExpression, expr->exp);
}
}
void Parser::onGlobal(Token &out, Token &expr) {
@@ -1616,6 +1600,10 @@ void Parser::onExpStatement(Token &out, Token &expr) {
void Parser::onForEach(Token &out, Token &arr, Token &name, Token &value,
Token &stmt) {
if (dynamic_pointer_cast<FunctionCall>(name->exp) ||
dynamic_pointer_cast<FunctionCall>(value->exp)) {
PARSE_ERROR("Can't use return value in write context");
}
if (value->exp && name->num()) {
PARSE_ERROR("Key element cannot be a reference");
return;
@@ -1681,23 +1669,28 @@ void Parser::onClosureStart(Token &name) {
onFunctionStart(name, true);
}
void Parser::onClosure(Token &out, Token &ret, Token &ref, Token &params,
Token &cparams, Token &stmts, bool is_static) {
Token func, name, modifiers;
void Parser::onClosure(Token &out, Token* modifiers, Token &ret, Token &ref,
Token &params, Token &cparams, Token &stmts) {
auto stmt = onFunctionHelper(FunctionType::Closure,
modifiers, ret, ref, nullptr, params, stmts, nullptr, true);
ModifierExpressionPtr modifier_exp = NEW_EXP0(ModifierExpression);
modifiers->exp = modifier_exp;
if (is_static) {
modifier_exp->add(T_STATIC);
ExpressionListPtr vars = dynamic_pointer_cast<ExpressionList>(cparams->exp);
if (vars) {
for (int i = vars->getCount() - 1; i >= 0; i--) {
ParameterExpressionPtr param(
dynamic_pointer_cast<ParameterExpression>((*vars)[i]));
if (param->getName() == "this") {
PARSE_ERROR("Cannot use $this as lexical variable");
}
}
}
onFunction(func, &modifiers, ret, ref, name, params, stmts, 0);
ClosureExpressionPtr closure = NEW_EXP(
ClosureExpression,
dynamic_pointer_cast<FunctionStatement>(func->stmt),
dynamic_pointer_cast<ExpressionList>(cparams->exp));
dynamic_pointer_cast<FunctionStatement>(stmt),
vars
);
closure->getClosureFunction()->setContainingClosure(closure);
out.reset();
out->exp = closure;
}
@@ -1710,7 +1703,7 @@ void Parser::onClosureParam(Token &out, Token *params, Token &param,
expList = NEW_EXP0(ExpressionList);
}
expList->addElement(NEW_EXP(ParameterExpression, TypeAnnotationPtr(),
m_scanner.hipHopSyntaxEnabled(), param->text(),
m_scanner.isHHSyntaxEnabled(), param->text(),
ref, 0, ExpressionPtr(), ExpressionPtr()));
out->exp = expList;
}
@@ -1728,7 +1721,7 @@ void Parser::onTypedef(Token& out, const Token& name, const Token& type) {
// currently).
auto const annot = type.typeAnnotation
? type.typeAnnotation
: boost::make_shared<TypeAnnotation>(type.text(), TypeAnnotationPtr());
: std::make_shared<TypeAnnotation>(type.text(), TypeAnnotationPtr());
auto td_stmt = NEW_STMT(TypedefStatement, name.text(), annot);
td_stmt->onParse(m_ar, m_file);
@@ -1788,7 +1781,7 @@ void Parser::nns(int token) {
getMessage().c_str());
return;
}
if (m_nsState == SeenNothing && token != T_DECLARE) {
if (m_nsState == SeenNothing && token != T_DECLARE && token != ';') {
m_nsState = SeenNonNamespaceStatement;
}
}
@@ -1909,7 +1902,7 @@ TStatementPtr Parser::extractStatement(ScannerToken *stmt) {
bool Parser::hasType(Token &type) {
if (!type.text().empty()) {
if (!m_scanner.hipHopSyntaxEnabled()) {
if (!m_scanner.isHHSyntaxEnabled()) {
PARSE_ERROR("Type hint is not enabled");
return false;
}
+62 -35
Ver Arquivo
@@ -17,30 +17,35 @@
#ifndef incl_HPHP_COMPILER_PARSER_H_
#define incl_HPHP_COMPILER_PARSER_H_
#include "hphp/runtime/base/util/exceptions.h"
#include "hphp/util/parser/parser.h"
#include "hphp/runtime/base/exceptions.h"
#include "hphp/parser/parser.h"
#include "hphp/compiler/construct.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/type_annotation.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/util/logger.h"
#ifdef HPHP_PARSER_NS
#undef HPHP_PARSER_NS
#endif
#define HPHP_PARSER_NS Compiler
#define LOG_PARSE_ERROR(file, line, fmt, args...) \
HPHP::Logger::Error( \
"HipHop Fatal error: " fmt " in %s on line %d", \
##args, \
(file), \
(line) \
)
#ifdef HPHP_PARSER_ERROR
#undef HPHP_PARSER_ERROR
#endif
#define HPHP_PARSER_ERROR(fmt, p, args...) \
do { \
if (HPHP::Option::WholeProgram) { \
HPHP::Logger::Error(fmt " %s", ##args, (p)->getMessage(true).c_str()); \
} \
throw HPHP::ParseTimeFatalException((p)->file(), (p)->line1(), \
fmt, ##args); \
} while (0)
#define HPHP_PARSER_ERROR(fmt, p, args...) \
throw HPHP::ParseTimeFatalException((p)->file(), (p)->line1(), fmt, ##args)
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -67,29 +72,36 @@ public:
m_text += str;
return *this;
}
Token &operator+(const Token &token) {
m_num += token.m_num;
m_text += token.m_text;
return *this;
}
Token *operator->() {
return this;
}
void operator=(int num) {
m_num = num;
}
void operator=(Token &other) {
Token& operator=(const Token& other) {
ScannerToken::operator=(other);
exp = other.exp;
stmt = other.stmt;
typeAnnotation = other.typeAnnotation;
return *this;
}
void reset() {
exp.reset();
stmt.reset();
typeAnnotation.reset();
ScannerToken::reset();
}
const std::string typeAnnotationName() {
return (typeAnnotation) ? typeAnnotation->fullName() : "";
}
@@ -100,7 +112,7 @@ public:
DECLARE_BOOST_TYPES(Parser);
class Parser : public ParserBase {
public:
static StatementListPtr ParseString(CStrRef input, AnalysisResultPtr ar,
static StatementListPtr ParseString(const String& input, AnalysisResultPtr ar,
const char *fileName = nullptr,
bool lambdaMode = false);
@@ -112,11 +124,11 @@ public:
virtual bool parseImpl();
bool parse();
virtual void error(const char* fmt, ...) ATTRIBUTE_PRINTF(2,3);
virtual bool enableXHP();
virtual bool enableFinallyStatement();
IMPLEMENT_XHP_ATTRIBUTES;
virtual void fatal(Location *loc, const char *msg);
virtual void fatal(const Location* loc, const char* msg);
virtual void parseFatal(const Location* loc, const char* msg);
std::string errString();
// result
@@ -219,12 +231,12 @@ public:
Token &stmt);
void onSwitch(Token &out, Token &expr, Token &cases);
void onCase(Token &out, Token &cases, Token *cond, Token &stmt);
void onBreak(Token &out, Token *expr);
void onContinue(Token &out, Token *expr);
void onBreakContinue(Token &out, bool isBreak, Token *expr);
void onReturn(Token &out, Token *expr);
void onYield(Token &out, Token &expr);
void onYieldPair(Token &out, Token &key, Token &val);
void onYieldBreak(Token &out);
void onAwait(Token &out, Token &expr);
void onGlobal(Token &out, Token &expr);
void onGlobalVar(Token &out, Token *exprs, Token &expr);
void onStatic(Token &out, Token &expr);
@@ -243,8 +255,8 @@ public:
void onThrow(Token &out, Token &expr);
void onClosureStart(Token &name);
void onClosure(Token &out, Token &ret, Token &ref, Token &params,
Token &cparams, Token &stmts, bool is_static);
void onClosure(Token &out, Token *modifiers, Token &ret, Token &ref,
Token &params, Token &cparams, Token &stmts);
void onClosureParam(Token &out, Token *params, Token &param, bool ref);
void onLabel(Token &out, Token &label);
void onGoto(Token &out, Token &label, bool limited);
@@ -272,29 +284,25 @@ public:
private:
struct FunctionContext {
FunctionContext()
: isNotGenerator(false)
: hasReturn(false)
, isGenerator(false)
, isAsync(false)
{}
// mark this function as generator; returns true on success
bool setIsGenerator() {
if (!isNotGenerator) isGenerator = true;
return !isNotGenerator;
}
// mark this function as non-generator; returns true on success
bool setIsNotGenerator() {
if (!isGenerator) isNotGenerator = true;
return !isGenerator;
}
void checkFinalAssertions() {
assert(!isGenerator || !isNotGenerator);
assert((isGenerator && !isAsync && !hasReturn) || !isGenerator);
}
bool isNotGenerator; // function determined to not be a generator
bool hasReturn; // function contains a return statement
bool isGenerator; // function determined to be a generator
};
bool isAsync; // function determined to be async
};
enum class FunctionType {
Function,
Method,
Closure,
};
AnalysisResultPtr m_ar;
FileScopePtr m_file;
@@ -324,8 +332,27 @@ private:
void newScope();
void completeScope(BlockScopePtr inner);
void invalidYield();
bool setIsGenerator();
void invalidAwait();
bool setIsAsync();
static bool canBeAsyncOrGenerator(string funcName, string clsName);
void checkFunctionContext(string funcName,
FunctionContext& funcContext,
ModifierExpressionPtr modifiers,
int returnsRef);
string getFunctionName(FunctionType type, Token* name);
void prepareConstructorParameters(StatementListPtr stmts,
ExpressionListPtr params,
bool isAbstract);
StatementPtr onFunctionHelper(FunctionType type,
Token *modifiers, Token &ret,
Token &ref, Token *name, Token &params,
Token &stmt, Token *attr, bool reloc);
ExpressionPtr getDynamicVariable(ExpressionPtr exp, bool encap);
ExpressionPtr createDynamicVariable(ExpressionPtr exp);
+1 -1
Ver Arquivo
@@ -81,7 +81,7 @@ int BlockStatement::getKidCount() const {
void BlockStatement::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_stmts = boost::dynamic_pointer_cast<StatementList>(cp);
m_stmts = dynamic_pointer_cast<StatementList>(cp);
break;
default:
assert(false);
+1 -1
Ver Arquivo
@@ -16,7 +16,7 @@
#include "hphp/compiler/statement/break_statement.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
+3 -3
Ver Arquivo
@@ -16,7 +16,7 @@
#include "hphp/compiler/statement/case_statement.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/option.h"
using namespace HPHP;
@@ -97,10 +97,10 @@ int CaseStatement::getKidCount() const {
void CaseStatement::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_condition = boost::dynamic_pointer_cast<Expression>(cp);
m_condition = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_stmt = boost::dynamic_pointer_cast<Statement>(cp);
m_stmt = dynamic_pointer_cast<Statement>(cp);
break;
default:
assert(false);
+3 -3
Ver Arquivo
@@ -107,13 +107,13 @@ int CatchStatement::getKidCount() const {
void CatchStatement::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_variable = boost::dynamic_pointer_cast<SimpleVariable>(cp);
m_variable = dynamic_pointer_cast<SimpleVariable>(cp);
break;
case 1:
m_stmt = boost::dynamic_pointer_cast<Statement>(cp);
m_stmt = dynamic_pointer_cast<Statement>(cp);
break;
case 2:
m_finallyStmt = boost::dynamic_pointer_cast<Statement>(cp);
m_finallyStmt = dynamic_pointer_cast<Statement>(cp);
default:
assert(false);
break;

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais