1251 Commits

Autor SHA1 Mensagem Data
Paul Tarjan 14e4d2d21c stop killing the socket until all data is sent
For small responses this was ok, since sending the data didn't take much time. For large requests, they would get truncated without this.

I checked for leaks by printing in the FastCGIConnection constructor and destructor and making sure they match up.

Closes #1631

Reviewed By: @simpkins

Differential Revision: D1147016
2014-01-29 11:24:08 -08:00
Fred Emmott 691535343a Fix incorrect ownerDocument after DOMDocument::createElement
Closes #1551

Fixed while investigating an ASAN failure when running PHPUnit's suite.

Reviewed By: @ptarjan

Differential Revision: D1144627
2014-01-28 16:14:37 -08:00
Fred Emmott 08fa42f2cb Fix memory management for xinclude nodes
Previously: ==580== ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x604400212103

We were recursively freeing the node, including the attribute nodes - however, libxml2 doesn't malloc them separately - all we needed to do was unlink and free the root.

This fixes a fatal in PHPUnit's test suite.

Reviewed By: @ptarjan

Differential Revision: D1144722
2014-01-28 16:14:21 -08:00
Fred Emmott a25e23a681 Fix spl_autoload_unregister($unused_but_valid_handler)
If a valid handler is passed in, but wasn't registered, we'd just remove the last one:

- find_if() would return ::end()
- erase() treats that to mean erase the last one

Behavior in the new test was:
- correctly remove 'b'
- incorrectly remove 'a' when asked to remove 'b' again
- segfault when asked to remove 'b' a third time

Reviewed By: @ptarjan

Differential Revision: D1145531
2014-01-28 16:13:52 -08:00
Fred Emmott 3504e7accf Fix scoping for evaling default ReflectionParameter values
Closes #1449
Closes #1652

Reviewed By: @ptarjan

Differential Revision: D1141045
2014-01-28 16:13:41 -08:00
Paul Saab 8f9ff8b3a4 Prevent garbage on DNS_TXT records
Bug #64458 fixed an off by one error when decoding TXT records
that resulted with garbage at the end of the string returned.

Reviewed By: @scannell

Differential Revision: D1146140
2014-01-28 16:12:55 -08:00
Camillus Gerard Cai 62c4857595 Define missing IMAGETYPE_ constants
Defined IMAGETYPE_UNKNOWN and IMAGETYPE_COUNT

Closes #1634
Closes #1638

Reviewed By: @ptarjan

Differential Revision: D1144855

Pulled By: @scannell
2014-01-28 16:12:48 -08:00
Stuart Loxton 99cfd7c3c7 Fix Zend strrpos compatibility
Fixes Zend strrpos compatibility and adds test.

Closes #1564
Closes #1632

Reviewed By: @bertmaher

Differential Revision: D1142139

Pulled By: @scannell
2014-01-28 16:12:40 -08:00
Erik 352bcbb504 Support for UNIX sockets
Add a new config param, Server.FileSocket. When
Server.FileSocket
is set it will be used inplace of a network socket for the primary
server. This uses a new parameter to ServerOptions, m_useFileSocket,
to toggle between treating the address as a socket path or a network
address.

To initialize a socket connection thrift expects the socket file to not
exist. To support this the 'something nice' retry in startServer will
unlink an existing socket only if fuser claims it is unused.
Server.EvilShutdown enables unlinking the socket regardless of current
users.

Closes #1594

Reviewed By: @ptarjan

Differential Revision: D1135876

Pulled By: @sgolemon
2014-01-28 16:10:41 -08:00
Paul Tarjan 3af6d9ae90 remove assert for ::class and make it fatal instead
If you do `parent::class` in a pseudomain you end up in this case. Zend gives this message in that case

Reviewed By: @elgenie

Differential Revision: D1140116

Conflicts:
	hphp/compiler/analysis/emitter.cpp
2014-01-28 13:49:40 -08:00
Paul Tarjan b8e48ac92d Implement ::class
Done mostly in the parser. There was one weird thing, traits have `self::CLASS` refer to themselves instead of the class that uses them. I had to do runtime support for `parent::CLASS` and `static::CLASS`.

Closes #1096

Reviewed By: @elgenie

Differential Revision: D1129169
2014-01-28 13:48:50 -08:00
Jim Radford 8561dc79d6 LdapLink::sweep shouldn't free smart allocated objects
LdapLink::sweep, avoid freeing smart allocated objects

Closes #1644

Reviewed By: @ptarjan

Differential Revision: D1144565

Pulled By: @scannell
2014-01-28 13:48:44 -08:00
Jim Radford a4f2211d79 UrlFile::sweep shouldn't free smart allocated objs
UrlFile::sweep shouldn't free smart allocated objs

Closes #1643

Reviewed By: @jdelong

Differential Revision: D1144563

Pulled By: @scannell
2014-01-28 13:48:39 -08:00
Paul Tarjan 6561d14139 support SCRIPT_FILENAME
Some fastcgi documentation doesn't tell you to pass all the params, only a handful. Even the official docs say this http://wiki.nginx.org/HttpFastcgiModule I think we should support the mode where we don't know the document root, jsut the absolute filename. I've already had to help 2 people in github with this issue so I think it is prevelant

Reviewed By: @scannell

Differential Revision: D1125309
2014-01-28 13:39:58 -08:00
Arnaud GRANAL 0772c54bb9 pfsockopen returns incorrect connections
Persistent connections currently return a cached connection for (key = "hostname").
Expected behavior is to return a cached connection for (key = "hostname + port").
As a result, persistent connections write and read from the wrong socket if you have multiple connections to the same hostname but different port.

Redis hhvm implementation is affected by this bug (probably other modules too, but not MySQL at least, who uses its own socket cache handler).

Closes #1599

Reviewed By: ps

Differential Revision: D1135971

Pulled By: @scannell
2014-01-28 13:35:45 -08:00
Sean Cannella 3c6d7674ec Add charset= support to PDO mysql DSN
Adds support for charset= in the PDO mysql DSN.

Closes #1309
Closes #1489

Reviewed By: @ptarjan

Differential Revision: D1137883
2014-01-28 13:35:10 -08:00
Ainsley Escorce-Jones 8cd216c0ab json_decode() parity with PHP 5.4
Added depth as the optional third parameter, there is now no
fixed maximum depth for the JSON parser, default depth is still 512, if
a user specifies a larger depth limit then the various stacks are
resized.

JSON_BIGINT_AS_STRING is now supported alongside the FB collection
options.

Closes #1470
Closes #1496

Reviewed By: @ptarjan

Differential Revision: D1117099

Pulled By: @scannell
2014-01-28 13:35:04 -08:00
Fred Emmott e3b61e5a9d Implement ini_get_all()
Used by PHPUnit, as triggered by Mockery

Reviewed By: @ptarjan

Differential Revision: D1136971
2014-01-28 13:34:50 -08:00
Fred Emmott ccebd2ff11 Move magic ini settings out of IniSettings
Pre-req on implementing ini_get_all() sanely.

Reviewed By: @ptarjan

Differential Revision: D1134579
2014-01-28 13:34:42 -08:00
Paul Tarjan 6087e04bf3 document --php
Closes #1610

Reviewed By: @jdelong

Differential Revision: D1145021
2014-01-28 13:34:06 -08:00
Alex Malyshev 8079b5c58e Don't use boost::to_upper
perf is showing that it's calling dynamic_cast, a lot.

Reviewed By: @jdelong

Differential Revision: D1136788
2014-01-28 13:24:12 -08:00
Paul Tarjan 10ddab3b1d keep around rawPostData just incase someone reads from php://input
What do you think about this? Usually we keep it around anyways in a global variable (`$HTTP_RAW_POST_DATA`) but that is possible to turn off, so we need a fool-proof place to put it to support `php://input`. Before this diff, the code only gave the last packet of the header in libevent and asserted on fastcgi.

Thoughts? I think it is worth supporting as the php docs says

http://www.php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data
... the preferred method for accessing the raw POST data is php://input.

Closes #1557

Reviewed By: afrind

Differential Revision: D1129130
2014-01-28 13:22:41 -08:00
Owen Yamauchi 140fe234fc Fix a sandcastle crash due to PGO mode
I'm only 95% convinced that this is the cause of a sandcastle crash.
We're not calling transCounterAddr with sequential translation ids
anymore (apparently) so it's possible that we need to allocate more than
one chunk of new counters.

I ran a sandcastle with this fix applied and it didn't crash, but the
crash wasn't 100% before, so you never know.

Reviewed By: @ottoni

Differential Revision: D1142512
2014-01-28 12:20:17 -08:00
aravind 9dec860d42 Revert "[hh] autoload: don't swallow fatals when autoloading"
: This reverts commit 78e4c601db4c0b6ce55b44ae201fedaf47b65501.

perf regression

Reviewed By: @jdelong
2014-01-28 12:20:17 -08:00
Guilherme Ottoni 247c911c5f Fix rare race condition keeping track of prologue callers
profileSrcKey() compares the request number with
Eval.JitProfileRequests to decide whether or not the given SrcKey will
be generated in profiling mode.  As a result, using profileSrcKey() to
decide whether a given prologue was generated in profile mode or not
was innaccurate: a caller generated in an older request (<
JitProfileRequests) would expect the prologue to be a Proflogue (since
it was JITed beforehand), but the prologue could have been created by
a concurrent, newer request (> JitProfileRequests), which generated the
prologue in non-profiling mode.

This diff fixes the problem by directly checking if the prologue
address is in the profile code section to determine whether it's a
Proflogue or not.

Reviewed By: aravind

Differential Revision: D1141101
2014-01-28 12:20:06 -08:00
Surupa Biswas 80a9ae11b2 Warnings for incorrect params passed to ReflectionProperty get/setValue
Added warnings to match Zend behavior for incorrect number of arguments passed
and for not passing an object as the first parameter when reflecting on instance properties.

Reviewed By: @ptarjan

Differential Revision: D1135118
2014-01-22 12:47:53 -08:00
Jordan DeLong 446a61b422 Fix 86pinit bug in hhbbc relating to collection initializers
I thought 86pinit could only set private properties to
uncounted types, but there's also collection literals.  Merge in
TInitCell---in these classes all private properties initialized by
86pinit will end up as TCell for now, since they start as uninit in
the scalar initializer.  (Things with non-scalar initializers also
will be TInitCell.)  We'll make it do better later.

Reviewed By: @dariorussi

Differential Revision: D1135293
2014-01-22 12:47:52 -08:00
Jordan DeLong 329527e19f Change indentation in lookup_constraint, add task# for a TODO
Reviewed By: @dariorussi

Differential Revision: D1134307
2014-01-22 12:47:52 -08:00
Jordan DeLong d45bc155e5 Add some logging to the assertions about unique classes actually being unique
I've hit this once or twice, and I think it probably is a
race in hphpc or something (it is not consistent).  Just add some
logging to try to help debug next time.  (So far it's always
Ix-related closure classes that have AttrUnique but actually aren't in
the cores I've had.)

Reviewed By: @swtaarrs

Differential Revision: D1135290
2014-01-22 12:47:52 -08:00
Fred Emmott 2762e7b5a0 Support ReflectionClass::getConstructor() for old-style superclass constructors
Reviewed By: @ptarjan

Differential Revision: D1132467
2014-01-22 12:47:52 -08:00
Sean Cannella 700026adc7 Merge pull request #1614 from skyfms/master
Allow disabling hardware counters from cmake
2014-01-22 07:47:32 -08:00
Edwin Smith 55212b92e9 Rename Interval::info -> loc in xls.cpp
Leftover from the RegisterInfo->PhysLoc rename.

Reviewed By: @bertmaher

Differential Revision: D1135841
2014-01-22 05:30:57 -08:00
bsimmers e31c664c02 Disable flaky zend test
Reviewed By: @bertmaher

Differential Revision: D1135985
2014-01-22 05:30:51 -08:00
Kristaps Kaupe e79df3c25e Allow disabling hardware counters from cmake. 2014-01-22 00:59:13 +02:00
Sean Cannella 204745bfe6 PHP_VERSION_ID should not be greater than all Zend
PHP_VERSION_ID is now 504999 which is > all Zend versions which
makes using it for comparisons of less than 5.5/5.6/etc. impossible.

Closes #1603

Reviewed By: @sgolemon

Differential Revision: D1135461
2014-01-21 11:20:15 -08:00
Guilherme Ottoni c7c45e0f04 Turn on the Region JIT (take 2)
Except for ARM.

Reviewed By: @swtaarrs

Differential Revision: D1119650
2014-01-21 11:20:11 -08:00
Drew Paroski 9793cd6059 Update Set to retain insertion order
Reviewed By: @elgenie

Differential Revision: D1129210
2014-01-20 10:12:32 -08:00
Rachel Kroll b82a14d235 Report thread ID in status pages
Reviewed By: tracelog

Differential Revision: D1134840
2014-01-20 10:09:09 -08:00
Paul Tarjan a13cb40a90 work on FastCGI perf
* parse all the fastcgi headers at once
* uppercase the key instead of using case insensitive. This won't return the original casing, but HTTP is case insensitive anyways, so it shouldn't matter *cross fingers*
* stop generating a vector in the header map and do it at readtime
* use `unordered_map`

Reviewed By: @jdelong

Differential Revision: D1128430
2014-01-20 10:09:06 -08:00
Dario Russi 7590d5e084 APC optimizations for arrays and strings to allow them to be shared "static" style.
Making APC strings and APC array with proper shape uncouted and truly shared in APC, saving on copy and ref count

Reviewed By: @jdelong

Differential Revision: D1114228
2014-01-20 10:09:03 -08:00
Joel Marcey f7ea7e74e1 Refactor the framework test script for better modularity and maintenance
I have wanted to break up run.php into its own files and refactor things a bit. So I am now doing that.

Note that the frameworks directory now contains the PHP for individual frameworks and that framework_downloads will contain the actual github code for the frameworks

During refactoring, I found some interesting new issues:

1. The recent changes to reflection (ext_reflection-classes.php, etc.) have caused my test finder to hiccup for cases where I find the tests with reflection. This may be bad code on my part; but I am not sure. Right now it seems the issues are coming with IsSubclassOf, but this is just a guess. I am trying to come up with a repo case.

2. The percentage of Magento2 has dropped into the upper 80% range. And this is due to some namespace fatals that are occurring. We need to dig into that. Note, that we are using a more recent git hash for Magento2 (instead of the August one as before) and they added more namespace support during that time. We are also seeing a drop in Drupal as well, but not to the same degree.

@ptarjan, this diff does not make the abstract Framework class public yet. That can be done in a subsequent diff :-)

Reviewed By: @ptarjan

Differential Revision: D1133446
2014-01-20 10:08:59 -08:00
Dario Russi 4ecab8ca94 Make $this available (aka not null) after it has been accessed once and subsequent code would have not run
after $this has been used (dereferenced) all subsequent accesses do not need to check for null

Reviewed By: @jdelong

Differential Revision: D1132614
2014-01-20 10:08:56 -08:00
Alex Malyshev 69a83741fc Support more of EG and PG in ext_zend_compat
Not all of the functions return references, so they can't be written to,
only read from.

Reviewed By: @ptarjan

Differential Revision: D1128247
2014-01-20 10:08:49 -08:00
bsimmers 6aa6d171e1 Add some asserts to the jit
These were all added while debugging an xls issue and they seem
generally useful.

Reviewed By: @edwinsmith

Differential Revision: D1132041
2014-01-20 10:08:45 -08:00
Bert Maher 2d6e5ba266 Pop stack before ContEnter
If we pop the stack after ContEnter, it creates a
LdStack/TakeStack that keeps an SSATmp live across a call, which
(rightfully) causes an assertion to fail later.

This isn't a problem if we have refcount opts or dce on, since those
passes will remove the TakeStack, but it would still be good to have
our IR correct in the absence of optimization.

Reviewed By: @swtaarrs

Differential Revision: D1134125
2014-01-20 10:08:42 -08:00
bsimmers c96f6e7c49 Make sure we don't throw without catch blocks
Some optimizations rely on being able to insert code on all exit
edges, so anything that can throw much have a catch block. This diff adds a
runtime check for that and fixes all cases I hit in local and prod testing.

Reviewed By: @edwinsmith

Differential Revision: D1132380
2014-01-20 10:08:39 -08:00
bsimmers e18f7406b0 Remove IRTrace from the jit
Exit traces are gone so this was fairly straightforward.

Reviewed By: @edwinsmith

Differential Revision: D1129611
2014-01-20 10:08:35 -08:00
bsimmers d7dba127d3 Purge exit traces from the jit
This diff eliminates all exit traces from the jit, turning them into
regular old Unlikely blocks in the main trace. IRTrace is still around and we
have one per IRUnit; I'm planning on eliminating it in a separate
diff. IRTrace's BlockList is gone, so now we just store a pointer to the entry
Block and walk the cfg from there.

Reviewed By: @edwinsmith

Differential Revision: D1128179
2014-01-20 10:08:31 -08:00
Sean Cannella 88d6079dc3 Fix server stats reporting
Fix server stats reporting

Reviewed By: @dariorussi

Differential Revision: D1133875
2014-01-20 10:08:28 -08:00
Fred Emmott 973c5847f2 Make SQLite3::version static
Depended on by codeigniter

Reviewed By: @ptarjan

Differential Revision: D1130812
2014-01-20 10:08:24 -08:00
Dario Russi e1d79f54d5 Update ir specification
IR opcodes added during lockdown had missing specifications

Reviewed By: @swtaarrs

Differential Revision: D1134268
2014-01-20 10:08:21 -08:00
bsimmers 58ddd23cec Disable flaky zend test
Reviewed By: @edwinsmith

Differential Revision: D1133886
2014-01-20 10:08:17 -08:00
Dario Russi cfaf436001 NewCol should push specific object types
NewCol and ColAddNewElemC should infer the proper collection type

Reviewed By: @jdelong

Differential Revision: D1129076
2014-01-20 10:08:13 -08:00
Eugene Letuchy ee4a6f7b35 misc: set error handler slightly differently in typehint_number test
... perhaps it will work better in repo mode if the test-installed error
handler always throws an exception, instead of relying on the return
value.

Reviewed By: @jdelong

Differential Revision: D1133463
2014-01-20 10:08:10 -08:00
Edwin Smith 47bc94d3a4 Enable xls by default
Flips the switch, and fixes computeLiveRegs() to account
for Shuffle destinations.

Reviewed By: @swtaarrs

Differential Revision: D1114596
2014-01-20 10:08:06 -08:00
Bert Maher daef8573ec Use getNativeFunctionName in Disasm
Get rid of duplicated code for demangling function names

Reviewed By: @swtaarrs

Differential Revision: D1132428
2014-01-20 10:08:02 -08:00
Evert Pot e93f235669 Added support for CURLOPT_POSTREDIR
Added support for CURLOPT_POSTREDIR

Closes #1477
Closes #1583

Reviewed By: @JoelMarcey

Differential Revision: D1131605

Pulled By: @scannell
2014-01-20 10:07:58 -08:00
Scott Renfro 9d74c2ce93 Change fb_utf8_substr() semantics to return '' on error
Already made the corresponding change in flib.  This
is more consistent with mb_substr() and more consistent with
a typed world -- fb_utf8_substr()'s return value will pass
typehints for strings, for example.

Reviewed By: @alokmenghrajani

Differential Revision: D493517
2014-01-17 14:46:18 -08:00
Jordan DeLong adaaaff943 Add .norepo to a test
I had this in the wrong diff, so broke trunk pushing a stack.

Reviewed By: @elgenie

Differential Revision: D1133199
2014-01-17 14:46:18 -08:00
Eugene Letuchy 8b247bafd1 'num' typehint
It's quite advantageous to be able to support int|float as a
 typehint without introducing support for full-blown unions. To make
 that equivalence happen, a bit of runtime support is necessary

Reviewed By: @jdelong

Differential Revision: D1128502
2014-01-17 14:46:00 -08:00
Owen Yamauchi 4fe752d8e5 Implement DecRef{Stack,Loc,Mem} in ARM mode
DecRefStack is the #2 punt. This involved a surprising amount of code.
Decreffing is hard, apparently.

Reviewed By: @edwinsmith

Differential Revision: D1131799
2014-01-17 01:43:53 -08:00
Jordan DeLong 4f56be3f8f Give up on private property inference on CreateCl opcodes
For now.  As is it can infer incorrect property types since
it isn't set up to look at the closure bodies.

Reviewed By: @dariorussi

Differential Revision: D1132987
2014-01-17 01:43:49 -08:00
Jordan DeLong eb8f8f3825 Fix several issues with type assert opcodes
Type assertions were allocating new DynLocations every time
we encountered them, which breaks getOutputUsage (it uses DynLocation
pointer equality to track the flow of values).  When encountering
assertions, it also wasn't doing the optimization that we have in
applyInputMetaData to eliminate earlier predictions on the same
location.  Finally, this diff finishes the support for optional object
types (fixes inlining and object property accesses in these
situations).

Reviewed By: @swtaarrs

Differential Revision: D1128602
2014-01-17 01:43:45 -08:00
Jordan DeLong 040e87ba69 Make type hint errors disallow recovery if repo was compiled with HardTypeHints
Fix a long-standing issue that could segfault the VM in
RepoAuthoritative mode (not in practice in www, since our error
handler always throws in this case).  To do this, adds a Repo global
metadata blob that we can use to communicate whatever global
compilation information we want to the runtime (I've wished we had
this for a few things in the past).

Reviewed By: @edwinsmith

Differential Revision: D1125218
2014-01-17 01:43:42 -08:00
Jordan DeLong 4be2cfd7d6 A few code review items I accidentally missed
Reviewed By: @edwinsmith

Differential Revision: D1126655
2014-01-17 01:43:38 -08:00
Jordan DeLong 8a8d6fe852 Returning from a function reads locals
Looking at the JIT's output with HHBBC on, I noticed guards
in tracelets that only do RetC weren't going away.  This is because I
forgot to tell the interpreter that return opcodes read locals, so the
assert opcodes weren't being added.

Reviewed By: @swtaarrs

Differential Revision: D1125188
2014-01-17 01:43:34 -08:00
Jordan DeLong f68a1d9c12 AssertObj opcode support for possibly-null types
I think for us to get anything from private property
inference, we have to be able to assert these types and rely on
tracelet guards to remove the nulls.

Reviewed By: @dariorussi

Differential Revision: D1125172
2014-01-17 01:43:30 -08:00
Jordan DeLong 78072ded36 Do better on bc::Clone of ?Obj<=Foo and ?Obj=Foo
A really small thing we needed to have the recently added
is_opt() and unopt() things to do.  Before it would just push TObj.
Now we can push the type with the possible null removed (since we'd
fatal if it was null).

Reviewed By: @dariorussi

Differential Revision: D1125107
2014-01-17 01:43:26 -08:00
Jordan DeLong 510881234a Infer that the Catch opcode always pushes a subclass of Exception
You can't throw non-Exception derived classes.  Also, catch
can't throw.

Reviewed By: @dariorussi

Differential Revision: D1125105
2014-01-17 01:43:23 -08:00
Jordan DeLong 19bd90df5e Use HNI return types in hhbbc's return type inference
We could do better for object types, but probably not worth
the effort yet until there's more conversion.

Reviewed By: @edwinsmith

Differential Revision: D1125101
2014-01-17 01:43:19 -08:00
nareshv 0acddafb3e Test runner improvements
- Added -i option to include only certain tests to be executed.
- Print the norepo reason next to skipped message for tests with .norepo
  file

Closes #1582

Reviewed By: @ptarjan

Differential Revision: D1131390

Pulled By: @scannell
2014-01-17 01:43:15 -08:00
Dmitry Panin 1445bce38d Fixed key collision in get_html_translation_table
in expression String::FromChar(i + em.basechar)
we casted "i + em.basechar" to char and therefore we got some
collisions of keys in translation table.
This diff uses more appropriate String::FromCStr as keys

Reviewed By: @ptarjan

Differential Revision: D1125958
2014-01-17 01:42:33 -08:00
Fred Emmott 0309f90d0f duplicate cell in rare loadCns path
- gets decrefed in frame_free_locals_helper_inl
- matches the behavior in the other non-error paths
- bsimmers is going to look at LookupCns - Uncounted is probably incorrect

Reviewed By: @swtaarrs

Differential Revision: D1130546
2014-01-17 01:42:28 -08:00
Owen Yamauchi 1c24482fa1 Delete unused exit edge support from DecRef instructions
These instructions never actually have an exit edge. Their flags in ir.h
indicate as much, as well as all of the places where they're gen()'ed.
All that code in code-gen was just cluttering up the place.

Reviewed By: @jdelong

Differential Revision: D1129774
2014-01-17 01:42:24 -08:00
Owen Yamauchi 5c6896ccd1 Implement LdFuncCached in ARM mode
This is the #3 punting opcode. The top two are Call and DecRefStack;
Call is in the works but proving to be rather nontrivial, and
DecRefStack is also going to be slightly tricky. This one, on the other
hand, is super simple.

Reviewed By: @edwinsmith

Differential Revision: D1129534
2014-01-17 01:40:54 -08:00
Joel Marcey 41f7f531fe Move the rest of the config to YAML
We started moving core config to YAML. Seems to work well. Let's move the rest over.

Reviewed By: @ptarjan

Differential Revision: D1130844
2014-01-17 01:40:54 -08:00
Guilherme Blanco fcba0889ad phpversion($extension) support
Implemented support for extension version check in phpversion()
following Zend compatibility. Updated all extensions on HHVM to match
versions on PECL and php-src master branch.

Closes #1506

Reviewed By: @JoelMarcey

Differential Revision: D1117334

Pulled By: @scannell
2014-01-17 01:40:54 -08:00
Fred Emmott e9b618ffe3 Reflection: use PreClass for method ordering and profiling info, Class for rest
Neither has sufficient data by itself

Reviewed By: @ptarjan

Differential Revision: D1129761
2014-01-17 01:40:54 -08:00
Paul Tarjan 3adf3d2994 fix test/run spew
Reviewed By: @swtaarrs

Differential Revision: D1129148
2014-01-17 01:40:54 -08:00
bsimmers 09c77a558f Change getNativeFunctionName to return a std::string
This is never used in perf-sensitive code and using std::string is
much cleaner and safer.

Reviewed By: @bertmaher

Differential Revision: D1126781
2014-01-17 01:40:53 -08:00
Bert Maher 8876047b0d Admin command for TC section addresses
It's nice to be able to ask the VM where the various TC
sections are.

Reviewed By: @ottoni

Differential Revision: D1128800
2014-01-17 01:40:53 -08:00
Guilherme Ottoni 8d55dfe117 Stop profiling translations at unconditional jumps
We should let the region selector decide whether or not to merge
profiling translations connected by an unconditional jump into a
longer trace.  So don't eagerly trace through unconditional jumps in
profiling mode.

Reviewed By: @edwinsmith

Differential Revision: D1128517
2014-01-17 01:40:53 -08:00
Alex Malyshev e2df82dc85 gd_info() had a misspelled string
Need "JPEG Support", not "JPG Support" to match Zend.

Reviewed By: @JoelMarcey

Differential Revision: D1128945
2014-01-17 01:40:53 -08:00
Herman Venter 40f82f5b6f Extract query parameter expressions from queries
Query expressions may contain sub expressions that can only be evaluated in the context of the query expression. These expressions effectively parameterize the query sent to the query engine (which typically runs out of process). Since query provider (which is distinct from the query engine) also runs in a separate context (albeit in the same thread) cannot evaluate these expressions in the right context, these expressions are replaced with references to compiler generated parameter variables in the expression tree sent to the query provider. When a query is evaluated, the values of the elided expressions are provided to the query method as additional arguments (the first argument being the expression tree). Note that the first elided expression is the receiver object for the query method call.

The extraction algorithm is a top down left to right traversal of the query AST that elides any expression which is not of a form that query processors are expected to be able to handle. The permitted forms are simple variables (that are bound to identifiers introduced by the query expression), constants, some unary operations, some binary operations, simple function calls and property accesses. If a sub expression of a permitted form is not itself permissible, it is replaced with a query parameter reference.

Reviewed By: @paroski

Differential Revision: D1124818
2014-01-17 01:40:53 -08:00
Paul Tarjan 0512e912e1 Don't use the Log.File in CLI
Right now we print both to stderr and the log file. Instead I think we should just ignore the option altogether in CLI mode. If we want to support that option we should support the INI setting http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log . The hdf option feels more like the apache log location than the php one.

Reviewed By: @jdelong

Differential Revision: D1085173
2014-01-17 01:40:53 -08:00
Joel Marcey 52de3ca164 Add Joomla CMS to the framework test runner
We have the Joomla framework, now let's add the CMS as well.

Reviewed By: @ptarjan

Differential Revision: D1128952
2014-01-17 01:40:52 -08:00
Emil Hesslow 470379e631 Fix for handling double backslashes
- The parser wasn't able to parse "as\\"

Reviewed By: @ptarjan

Differential Revision: D1128312
2014-01-17 01:40:52 -08:00
Emil Hesslow 7ee169a7eb New try to get in the ini parser stuff
- This rerevert D1116195 and D1116199
- It also fixes a problem when ini files contains junk. So instead of outputing junk on stdout it now fails parsing those files
- I also went re-run a bunch of tests that now passes.

Reviewed By: @ptarjan

Differential Revision: D1127923
2014-01-17 01:40:52 -08:00
Emil Hesslow 36eac72b6e Re-import ext/standard/tests/general_functions
tools/import_zend_test.py -z ~/php-src-PHP-5.5/ -o ext/standard/tests/general_functions

Reviewed By: @ptarjan

Differential Revision: D1127780
2014-01-17 01:40:52 -08:00
Kristaps Kaupe f2e996ade1 clang fixes
Fix a few clang warnings / errors.

Closes #1570

Reviewed By: @alexmalyshev

Differential Revision: D1128347

Pulled By: @scannell
2014-01-17 01:40:52 -08:00
Eugene Letuchy 53ffeac06d autoload: don't swallow fatals when autoloading
For a nonexistent class for which the autoloader map knows a file is
 present known, the autoload should behave the same way as if a
 require_once were made to that file and propagate any fatals that
 result. If on the other hand, the file for the class was unknown or
 the class was not successfully loaded (but there was no fatal), we
 continue to call the userspace-supplied faiure callback function.

Reviewed By: @ptarjan

Differential Revision: D1122740
2014-01-17 01:40:52 -08:00
Eugene Letuchy 4aeb3e599e collections: template vector::filter|map ...
... to allow versions with callbacks that take values only vs
 keys-and-values to reuse code.

Reviewed By: @jdelong

Differential Revision: D1127092
2014-01-17 01:40:52 -08:00
Eugene Letuchy 2097d7947d collections: share code between Map::->foo and ->fooWithKey
Hella templates for higher order collection functions:
 - map (+withKey)
 - filter (+withKey)
 - retain (+withKey)

Reviewed By: @jdelong

Differential Revision: D1126448
2014-01-17 01:40:51 -08:00
Eugene Letuchy 252f67b99b collections: add retain() and retainWithKey() to {Map|StableMap}
... the in-place mutating cousin of filter, retain takes a
 predicate callback for each entry in the map and uses the return
 value to determine whether to keep the element around.

 Deferring ##Vector## and ##Set## (easy).

Reviewed By: @jdelong

Differential Revision: D1121508
2014-01-17 01:40:51 -08:00
Fred Emmott 39a5e928aa Implement ReflectionParam::__toString
Used by Mockery to get type hint values. I'm submitting a diff to Mockery to make it use getTypehintText if available, but this should be implemented anyway.

Added two tests - one for confirming we're Zend-compatible (with .expect generated by Zend), the other for checking that non-null defaults work for basic-type typehints (which aren't supported by Zend)

Reviewed By: @ptarjan

Differential Revision: D1127714
2014-01-17 01:40:51 -08:00
javer 2091a8114d Fix memory leak in PDO::fetchAll()
Fix memory leak when fetching data using PDO::fetchAll().

Closes #1569

Reviewed By: @JoelMarcey

Differential Revision: D1128106

Pulled By: @scannell
2014-01-17 01:40:51 -08:00
Jordan DeLong 1c3aa1bf3d Abort when Repo::Repo fails instead of calling exit()
This can fail if we're out of file descriptors.  Calling exit
while other threads are still running leads to bad crashes in random
places, depending on the order that global destructors get run.
Instead let's always_assert with a message.

Reviewed By: @scannell

Differential Revision: D1125004
2014-01-17 01:40:51 -08:00
Antony Puckey ea14973c5e add getRemoteAddr to transport which defaults to empty string.
add getRemoteAddr to fastcgi transport to return the proper header. if no remoteAddr set it to the remoteHost ( libevent ) only set REMOTE_HOST if there is something in it as per php-src

Closes #1559

Reviewed By: @scannell

Differential Revision: D1126545

Pulled By: @ptarjan
2014-01-17 01:40:51 -08:00
Alex Malyshev b44e9c1889 Remove 'static' from function declared in a separate header
collectionDeepCopyBaseMap declared in ext_collections.h, but defined in
ext_collections.cpp. No idea why gcc doesn't catch it.

Reviewed By: @elgenie

Differential Revision: D1127006
2014-01-17 01:40:50 -08:00
bsimmers 60821e0166 Refactor TranslatorX64's CodeBlocks into a CodeCache module
I did this in preparation for something which ended up not working
out, but this could be worth keeping.

Reviewed By: @oyamauchi

Differential Revision: D1125965
2014-01-17 01:40:50 -08:00
Emil Hesslow 91c03c40a4 A bunch of different CSV fixes
- Do a bunch of small changes to make HHVM error when Zend does

Reviewed By: @ptarjan

Differential Revision: D970379
2014-01-17 01:40:50 -08:00
Sara Golemon 220a453220 Change docskel.php to use a local phpdoc checkout rather than svn.php.net
Runs MUCH faster this way.

Reviewed By: @ptarjan

Differential Revision: D1126413
2014-01-17 01:40:50 -08:00
Paul Tarjan 33dfe04716 time before sudo 2014-01-16 17:50:07 -08:00
Paul Tarjan b60492db9c See how long each step takes 2014-01-16 17:32:27 -08:00
ptarjan 5caac83428 remove folly files that were removed 2014-01-16 15:50:13 -08:00
ptarjan 08edc30657 update folly so there isn't two IOBuf.cpp files 2014-01-16 15:38:22 -08:00
mwilliams 7eb3262d3d Dont ignore errors from FT_Get_Glyph
"image" is left uninitialized if we do.

Reviewed By: @scannell

Differential Revision: D1126277
2014-01-14 11:42:01 -08:00
Joel Marcey 42795f08a5 Use Yaml for framework test runner configuration. Add github url to it too.
Yaml just seems cleaner and overall better for this type of configuration.

Decided to use a PHP YAML parser to avoid having to turn on EnableZendCompat explictly at the command line, particularly in open source.

So chose: https://github.com/mustangostang/spyc

Reviewed By: @ptarjan

Differential Revision: D1127123
2014-01-14 11:42:00 -08:00
Simon Welsh aa173f6ce8 Change ext/reflection from IDL to HNI
Change ext/reflection from IDL to HNI.

Also adds HNI support for HipHopSpecific through the
__HipHopSpecific user attribute. Code that wants to check for this
should use Func::getFuncInfo(mi) instead of Func::methInfo() (I only saw
Reflection using it).

Closes #1484

Reviewed By: @JoelMarcey

Differential Revision: D1124639

Pulled By: @scannell
2014-01-14 11:41:54 -08:00
Sean Cannella 9a35c755d3 Fix missing include in OSX
One more missing include on OSX in util/

Reviewed By: @alexmalyshev

Differential Revision: D1126910
2014-01-14 11:41:35 -08:00
Drew Paroski 7ded25076f Rename Set::difference() to Set::removeAll()
The difference method is confusingly named; its name does not imply that it
modifies the original Set. This diff renames "difference" to "removeAll" to
make it clearer. Eventually the difference() method will be removed after
all callers have been updated.

Reviewed By: @elgenie

Differential Revision: D1120227
2014-01-14 11:41:34 -08:00
Simon Welsh a464ad28e8 Convert ext/bzip2 to HNI
Adds error handling to the bzerr*() functions, allowing one of
the current bad tests to pass.

Closes #1547

Reviewed By: @sgolemon

Differential Revision: D1125459

Pulled By: @scannell
2014-01-14 11:41:27 -08:00
Antony Puckey f1fdcdd8ab Set HTTPS header appropriately in fastcgi
Check passed header values for HTTPS.

IIS sets this header to "off" so check for that and empty value before
using transport->setSSL().

Only change to lower case if the value is not empty for performance.

Closes #1546

Reviewed By: @ptarjan

Differential Revision: D1125440

Pulled By: @scannell
2014-01-13 15:58:06 -08:00
Simon Welsh 1914e07d21 Convert ext/phar to HNI
Closes #1548

Reviewed By: @sgolemon

Differential Revision: D1125469

Pulled By: @scannell
2014-01-13 15:57:58 -08:00
Edwin Smith 35a0406935 Rename hphp-value.cpp/h to typed-value
Since it defines class TypedValue

Reviewed By: @bertmaher

Differential Revision: D1125416
2014-01-13 15:20:10 -08:00
Paul Tarjan 9762e8fb56 fix fastcgi segfaults a better way
I think this is what julk originally wanted. He has a `m_keepConn` boolean that is set by `ConnectionFlags::KEEP_CONN` and if that is false, he calls this callback in both the error and the success case.

This doesn't segfault when the connection is abruptly closed by the requestor.

Closes #1522

Reviewed By: @scannell

Differential Revision: D1124995
2014-01-13 15:20:06 -08:00
Bert Maher 3b6d74078f Add FP, SP to hhirTracelet tracing
Adding this was pretty helpful for tracking down a stack
corruption bug.

Reviewed By: @swtaarrs

Differential Revision: D1125781
2014-01-13 15:20:03 -08:00
Jordan DeLong 73d02b43e9 Clean up a few TODOs relating to analyzing builtins in hhbbc
Some cases in class resolution that were happening for
builtins now won't (I checked).  They are mostly just "in principle"
possible now, and shouldn't really happen as far as I know aside from
one case: if you put "implements Foo" and Foo is actually a class.  I
can't get hphpc to mark AttrUnique on anything that would fail in
those places other than that.

Reviewed By: @edwinsmith

Differential Revision: D1125093
2014-01-13 15:19:56 -08:00
Jordan DeLong 2906fe6c98 Missing things in HHBBC representation: HNI types and isAsync
Now that HHBBC compiles systemlib, it needs to support
passing HNI-native function return types.  Also I apparently missed
isAsync only on the parse side (a newish test caught it).

I made native info a struct even though it only has one thing so
far---I think later we'll want the function pointer and a flag about
whether we can invoke it with constant arguments during compilation
time.

Reviewed By: @edwinsmith

Differential Revision: D1125080
2014-01-13 15:19:52 -08:00
Jordan DeLong d0a7b63495 Fix hhbbc issues with magic builtin interfaces (KeyedTraversable, etc)
After turning on hhbbc on systemlib, these interface names
are statically resolved, so it was assuming things like $x instanceof
Traversable is only true if $x is an object, and that an array
couldn't pass one of those parameter type hints.

Reviewed By: @dariorussi

Differential Revision: D1125061
2014-01-13 15:19:49 -08:00
Jordan DeLong d145f254e6 Use tbb::concurrent_hash_map for the Index dependency map
It was previously just a std::mutex around a
std::unordered_map, which seems to be a big source of contention after
putting systemlib is in the mix.

Reviewed By: @edwinsmith

Differential Revision: D1125048
2014-01-13 15:19:45 -08:00
Jordan DeLong a8111978fa Add support for "bumping" trace levels, use it to not trace systemlib in hhbbc
Use this so systemlib units will only be traced if the level
is higher than normal.

Reviewed By: @edwinsmith

Differential Revision: D1125039
2014-01-13 15:19:42 -08:00
Jordan DeLong cabe7cc3a7 Let systemlib units go through hhbbc
After the change to include systemlib in hphpc's static
analysis, I temporarily cut them out of whole_program in HHBBC.  The
problem was just that systemlib needs to end up merge only, but none
of hhbbc's output units are merge only.  Solve this with a special
case in emit.cpp for now.

This seems to make a ~2x slow down in how long the first analyze pass
takes hhbbc.  I think the reason is that now *tons* of things are
registering dependencies to common builtins that didn't use to
(e.g. idx)---it seems to be spending a lot of time on the single lock
there now.  (Will probably change it to tbb ...)

Reviewed By: @dariorussi

Differential Revision: D1125024
2014-01-13 15:19:39 -08:00
Jordan DeLong fd00ef394e Remove includes of util.h from .cpp files in hphp/util
Replace some uses with folly functions or boost.  I kept
string_vsnprintf in its own header for now.  We could probably move it
to folly/String.h (folly has stringPrintf and such, just no vararg
version), but on the other hand using va_list is not very encouraged
so maybe we should just leave it here for these legacy uses.

Reviewed By: @ptarjan

Differential Revision: D1124742
2014-01-13 15:19:32 -08:00
Jordan DeLong 7ccb4ef44f Remove includes of util.h from util/ headers
Few of them were using functions exported by util.h, they
were just using it to grab things like std::map.  Fixed some
downstream direct-includes.  Where trivial, used folly or boost
instead of Util::.

Reviewed By: @ptarjan

Differential Revision: D1124738
2014-01-13 15:19:28 -08:00
Jordan DeLong e26c7caf12 Move LogFileFlusher to its own header
Out of util.h.  For now, put drop_caches into
compatability.h, but that could easily turn into a blob-header also if
we're not careful.  Also made some style changes: make the virtual
private (virtual functions should rarely be protected), override
keyword, non-static member initializer, s/class/struct/.

Reviewed By: @edwinsmith

Differential Revision: D1124736
2014-01-13 15:19:25 -08:00
Jordan DeLong 63893eecb4 Remove s_file_mutex from util.cpp
Apparently dead.

Reviewed By: @bertmaher

Differential Revision: D1124735
2014-01-13 15:19:21 -08:00
Fred Emmott ee1e4278f0 HHVM MySQL corrections for bogus connections
Followup to https://github.com/facebook/hhvm/commit/76cab4dd67c3b20ad64927ada9bd71d0c4

Reviewed By: @ptarjan

Differential Revision: D1124285
2014-01-13 15:19:05 -08:00
bsimmers 624945ba03 Document TakeStack better, emit it in fewer situations
There was no obvious context for why it was being emitted in
simplifyLdStack, and we don't need to emit it if the new value is already from
a raw load.

Reviewed By: @edwinsmith

Differential Revision: D1114188
2014-01-13 15:19:01 -08:00
bsimmers 15a3e7b0d5 Print test commands when --verbose is present in test/run
Sometimes I want to see the command to run a test even if it's not
failing.

Reviewed By: @ptarjan

Differential Revision: D1114189
2014-01-13 15:18:57 -08:00
Bert Maher 3e52a380a2 Don't preemptively optimize away conditional jumps
There may be a stack adjustment needed.

Reviewed By: @ottoni

Differential Revision: D1124766
2014-01-13 15:18:50 -08:00
Owen Yamauchi ee2f2d18cb Implement codegen for LdLoc, IncRef, AssertType
LdLoc was the goal here (it was by far the most frequent punt). It's
really simple to implement, but it turned out that doing codegen for it
had a few cascading effects.

- We're now carrying registers across InterpOne calls, so switch to
  using cgCallHelper there.

- Using cgCallHelper for interp-one now requires cgCallHelper to support
  immediate arguments to helpers.

- IncRef and AssertType are now generated in such a way that we can't
  punt on them (even if you punt on them, they show up in
  hhbc-translator output).

Reviewed By: @edwinsmith

Differential Revision: D1120272
2014-01-13 10:11:11 -08:00
Daniel Sloof 42b810671f Fix valgrind issue in Github build
This fixes a JIT crash with VALGRIND=1.

Closes #1483

Reviewed By: @ptarjan

Differential Revision: D1117038

Pulled By: @scannell
2014-01-13 10:11:07 -08:00
Owen Yamauchi e8e49bd45e Implement the equivalent of CALL_OPCODE for ARM
This gets the native-call machinery working on ARM. I tried hard to
avoid copypasta, but unfortunately I think some amount of it is
inevitable.

I've only converted one of the simplest possible opcodes (ConvIntToStr)
for now, because I've knowingly punted on some stuff for now, most
notably arguments passed on the stack. This diff gets the basics in
place; in future diffs I'll convert more opcodes and iron out the issues
that arise.

- shuffleArgs(), like SpillStack, is another one of those annoying cases
  where most of the logic is platform-independent but there are several
  instruction-emitting calls buried deep down.

- I moved ArgDesc and ArgGroup into their own file, which was fairly
  smooth, especially now that PhysReg isn't x64-specific.

- I split out Immed from asm-x64.h because it's not x64-specific and
  ArgDesc depends on it.

Reviewed By: @edwinsmith

Differential Revision: D1121726
2014-01-13 10:11:04 -08:00
Paul Tarjan d9ca0e9feb disabled tests
Including the disabled tests for mongo so I can slowly enable them

Reviewed By: @paroski

Differential Revision: D979400
2014-01-13 10:10:59 -08:00
Paul Tarjan d037846e9e return false for bad preg_match
Closes #1347

Reviewed By: @JoelMarcey

Differential Revision: D1125164
2014-01-13 10:10:53 -08:00
Paul Tarjan fe8075951a remove StaticContentCache scan at startup
This was added many moons ago for static content perf. Basically we scanned whatever was on disk and made a map of all the file extensions we wanted to serve. We also allow files to be loaded from disk if `EnableStaticContentFromDisk` is set (which is default on).

Having this was bad for fastcgi since `SourceRoot` doesn't even make sense there.

Reviewed By: @jdelong

Differential Revision: D1124447
2014-01-13 10:10:48 -08:00
Paul Tarjan 0e20e402d9 Support mod_fastcgi
when using mod_fastcgi SCRIPT_NAME is the Action instead of the actual document you want
this commit uses PATH_TRANSLATED - DOCUMENT_ROOT

tested with:
apache+mod_fastcgi
apache+mod_proxy_fcgi
nginx with no PATH_TRANSLATED header
nginx with this as PATH_TRANSLATED: fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name;

Reviewed By: @scannell

Differential Revision: D1114124
2014-01-13 10:10:44 -08:00
Dario Russi 2f7661c7a2 Call iterNext indirectly via table with heavily specialized helpers
Make iterNext and iterNextK super specialized helpers and invoke via indirect call instead of call to single helper

Reviewed By: @paroski

Differential Revision: D1084030
2014-01-13 10:10:39 -08:00
Dario Russi 00514c2f3b Remove APC stats
We are moving away from unused stats and start moving the stats to a more sensible infrastructure

Reviewed By: @jdelong

Differential Revision: D1110559
2014-01-13 10:10:34 -08:00
Sara Golemon ba8b4bf75a Implement Intl's DateFormatter class
This is actually a partial implementation because DateFormatter
is tightly bound to IntlCalendar (and its children).
Rather than make a massive hard-to-review diff,
I've implemented most of the DateFormater bits here
and will finish them off with a followup IntlCalendar diff.

Reviewed By: @ptarjan

Differential Revision: D1119360
2014-01-11 18:11:05 -08:00
Jordan DeLong 2abbadcec1 Don't restrict auto-alias names to the global namespace
In practice, this is a bit surprising behavior for code in
<?hh mode that also uses namespaces.

Reviewed By: @dariorussi

Differential Revision: D1120068
2014-01-11 18:11:02 -08:00
Paul Tarjan 4066a94d2e stop emitting regex debugging message
This message is breaking composer installing things with enormous regexes. I tried to change the default error level but @markw65 didn't like that and we need to do something, so I guess lets not emit this if EHHS is off.

Closes #1347

Reviewed By: @markw65

Differential Revision: D1118365
2014-01-11 18:10:58 -08:00
Guilherme Ottoni f9c54437b2 Initialize all fields in NormalizedInstruction's constructor
I noticed various fields weren't being initialized there while
investigating a failure with the region JIT that seems related to
uninitialized memory.  This doesn't fix the failure, but seems worth
fixing anyway.

Reviewed By: @scannell

Differential Revision: D1123322
2014-01-11 18:10:51 -08:00
Jordan DeLong f6c9f5ebf6 Fix ReflectionFunction for closures with uninitialized static locals
ReflectionFunction::getStaticVariables returns both use vars
and closure static locals.  In zend, if there are name conflicts
between the two sets, things get weird (see task #3499967).  Also, in
zend, the value of the static is computed at closure allocation time,
which means calling this on an unevaluated closure gives the static's
value.  For us, the closure has to be invoked to execute a
StaticLocInit (prior to that, the 86static_foo property is
KindOfUninit, so we'd raise the notice @elynde hit).

This changes things to not raise when reading properties (only the
statics could be uninit), and strip the 86static_ prefix, which is
closer to what zend shows.  But we're still a bit different...

Reviewed By: @ptarjan

Differential Revision: D1120161
2014-01-11 18:10:48 -08:00
Simon Welsh d963fa2019 Handle unserializing a finfo object.
Zend currently throws:
Warning: finfo::file(): The invalid fileinfo object.
when trying to do something on an unserialised object. I consider this a
bug in Zend and there doesn't appear to be any tests covering that
behaviour.

This currently segfaults when deconstructing the unserialised object in
HHVM.

Closes #1527

Reviewed By: @ptarjan

Differential Revision: D1123430

Pulled By: @scannell
2014-01-11 18:10:44 -08:00
Patryk Pomykalski 4607dcf3a0 Mongodb hacks and test
For testing zend compatibility bugs.

Closes #1479

Reviewed By: @scannell

Differential Revision: D1117041

Pulled By: @ptarjan
2014-01-10 15:30:48 -08:00
Simon Welsh 8dfad03dfa Convert ext/bcmath to HNI
Converts ext/bcmath to HNI and adds support for scaling

Closes #1534

Reviewed By: @sgolemon

Differential Revision: D1123805

Pulled By: @scannell
2014-01-10 15:30:42 -08:00
Fred Emmott 3d9cfbea18 Fix rendering DateTime objects with offset TZs
- m_tz and m_time/tz_info are only relevant if m_time->zone_type == 3
 - if zone_type == 1, m_time->z is the only relevant thing
 - however, there can still be something completely irrelevant in tz_info - and format() was using this to find the offset
 - call offset() instead of asking the tz_info for it

Closes #1406

Reviewed By: @ptarjan

Differential Revision: D1120967
2014-01-10 15:22:41 -08:00
James Miller faaaa3b646 Fix namespace typedefs
Typedefs weren't being normalized, so checks that should have
worked, didn't.

Closes #1526

Reviewed By: @gabelevi

Differential Revision: D1123427

Pulled By: @scannell
2014-01-10 15:22:07 -08:00
Sara Golemon 9593a491df Use pkg-config to find freetype2 and clean up cmake module
This was doing clowny things including looking for a
header that we're not interested in using.

Closes #1380
2014-01-10 11:28:00 -08:00
Joseph Marrama 3cf3ba4497 Fix the build with the newer versions of libdwarf
This fixes an error with inconsistent types being used for the 'name'
parameter when registering a libdwarf callback against newer versions
of libdwarf (versions where the 'name' parameter is a const char*).

I verified that this compiles with the latest version of libdwarf.

Closes #1525

Reviewed By: @alexmalyshev

Differential Revision: D1122805

Pulled By: @scannell
2014-01-10 09:44:22 -08:00
Alex Malyshev 2cba5eda8e vm_decode_function doesn't verify parent has __call[Static]
When running call_user_func(array('C', 'parent::doesntExist')), Zend
runs C::__call if it exists and if the parent of C also has a
__call method. We were just checking C.

Closes #1471

Reviewed By: @ptarjan

Differential Revision: D1121885
2014-01-10 09:44:18 -08:00
Bert Maher 220245cb53 Miscellaneous cleanup of Array
This is basically just moving things around to make the API
more obvious and conform to our general coding style.

Reviewed By: @edwinsmith

Differential Revision: D1121410
2014-01-10 09:44:11 -08:00
Bert Maher d03733937f Remove Array::lval since it basically duplicates Array::lvalAt
Array::lval is almost identical; it just requires that
AccessFlags::Key be passed where string-integer keys can be created
(e.g., dynamic object properties).

Reviewed By: @markw65

Differential Revision: D1121403
2014-01-10 09:44:07 -08:00
Joel Marcey 383b963111 Move frameworks to master or develop branches
Move all the frameworks away from just specific git hashes to a master, develop (or equivalent) branch.

We start off with specific git hashes for the branch, but now there is a --latest and --reset option that gets the latest source for that branch and updates our new frameworks.json file with the latest hash.

I will do a --reset after this diff is approved to get new .expect files, etc.

Reviewed By: @ptarjan

Differential Revision: D1099135
2014-01-10 09:43:56 -08:00
Herman Venter 5922bf689d Add Code Model support for "require extends class" and "require implements interface" statements.
Added templates for two new statement types. Added serialization support. Added references to these types to the generator scripts.

Reviewed By: @elgenie

Differential Revision: D1118441
2014-01-10 09:43:49 -08:00
Alex Malyshev e08ed9c636 New round of clang-3.4 fixes
* clang doesn't like that a lambda without a return type can return
  either T or const T

* Template function was declared as non-static but defined as static

* Unused variables on findPassFP

Reviewed By: @jdelong

Differential Revision: D1121470
2014-01-09 11:22:15 -08:00
Sean Cannella c95c0c0210 Fix systemlib lint errors
Fix systemlib lint errors

Reviewed By: @markw65

Differential Revision: D1121699
2014-01-09 11:22:12 -08:00
Fred Emmott 76cab4dd67 Fix several MySQL segfaults when passing invalid connection IDs
Converts ID to pointer, wasn't checking the pointer was valid. Warnings are already raised by the lookup function.

These appear to all be functions that don't exist in Zend. Based behavior on existing code when returning bools, libmysql documentation when returning ints.

Closes #1297
Closes #1295
Closes #1296
Closes #1294

Reviewed By: @ptarjan

Differential Revision: D1120382
2014-01-09 11:22:08 -08:00
Fred Emmott 5bb1d221ff Fix xmlwriter_open_uri with no actual output
3 crashes fixed :)

- don't try and write 0 bytes. this makes no sense, and assert-fails for some URIs, including PlainFile
- Take ownership of m_uri
- libxml2 owns what was m_uri_output. Don't double-free.

Closes #1293

Reviewed By: @markw65

Differential Revision: D1119825
2014-01-09 11:22:02 -08:00
Antony Puckey 089a18e65f Populate fastcgi (transport-specific) headers
Added new function CopyServerParams in http-protocol which uses the new transport function getServerParams that adds any transport specific SERVER variables ie: FASTCGI_PARAMS to the _SERVER array

Closes #1437
Closes #1511

Reviewed By: @sgolemon

Differential Revision: D1120838

Pulled By: @scannell
2014-01-09 11:21:55 -08:00
Paul Tarjan d5659d79d2 don't rely on the COMPILE_DL_ thing to create the extension
thanks to the awesome @andralex we not longer have to hook into the thing that was inside an ifdef. This should fix lots of problems in the OSS build.

Basically we are now relying on the implicit copy constructor of `char *` to `ZendExtension` to register the extension.

Reviewed By: @sgolemon

Differential Revision: D1119700
2014-01-09 11:21:48 -08:00
Eugene Letuchy eeca955c97 collections: collapse base_vector.{h,cpp} into ext_collections
... this allows ExtCollectionObjectData to move out of
 object-data.h and resolves inconsistency between `BaseVector` and its
 cousins `BaseMap` and `BaseSet`. This diff is just a copy-paste: no
 changes were made in the added lines.

Reviewed By: @paroski

Differential Revision: D1120174
2014-01-09 11:21:45 -08:00
Edwin Smith 1bd963d868 Get rid of forEachTraceInst()
Each place we use it, we can do an iteration over reachable
blocks instead.

Reviewed By: @ottoni

Differential Revision: D1118394
2014-01-09 11:21:41 -08:00
Guilherme Ottoni 815939f497 Fix race in bind-call service request
The prologue we're binding to may change while the thread waits for the write lease, so read the latest value after acquiring the write lease.

Reviewed By: @scannell

Differential Revision: D1120488
2014-01-09 11:21:34 -08:00
Alex Malyshev 72ced07376 Replace ArrayIter* with ArrayIter in DOMNodeIterator
Don't know what the point was with using an ArrayIter* in the first
place. It was being deleted in c_DOMNodeIterator::sweep(), which would
try to decRefAndRelease() the ArrayData and hit an assert in
MemoryManager.

Reviewed By: @ptarjan

Differential Revision: D1109230
2014-01-09 11:21:23 -08:00
Fred Emmott 87670afba5 Allow passing a node to DOMDocument::saveHTML
Also, change behavior of saveHTML() to match formatting options of Zend (required for this test to pass)

Closes #1099

Reviewed By: @ptarjan

Differential Revision: D1119532
2014-01-09 11:21:13 -08:00
Eugene Letuchy 27580ef53f update NEWS for recent collections + trait changes
Reviewed By: @scannell

Differential Revision: D1120107
2014-01-09 11:21:09 -08:00
Eugene Letuchy 522cf50eb0 collections: remove default: case from switch(CollectionType)
... to take advantage of the compiler warnings for using `switch` on
 an enum and not covering all the cases. After this diff, adding new
 collection types should now be much easier, since the compiler should
 be able to ferret out (most of) the missing functionality.

Reviewed By: @jdelong

Differential Revision: D1120079
2014-01-09 11:21:05 -08:00
Eugene Letuchy 88f72709b8 collections: remove <Collection>::put(k,v) method ...
... which has been deprecated in favor of set(k,v) for some time

Reviewed By: @jdelong

Differential Revision: D1120043
2014-01-09 11:21:01 -08:00
Eugene Letuchy dd79d86fa9 collections: introduce ExtCollectionObjectData
... instead of making various collection constructors set the
 object data attributes.

Reviewed By: @jdelong

Differential Revision: D1120031
2014-01-09 11:20:58 -08:00
Eugene Letuchy 7759020ffd collections: support frozen<collection> == <collection>
It seems like equality comparison within subtypes of
 {Vector,Set,Map} should be supported.

Reviewed By: @paroski

Differential Revision: D1117505
2014-01-09 11:13:59 -08:00
Eugene Letuchy 044b1a86e8 collections: add HH\FrozenMap
- parser transform for "FrozenMap" in HH\FrozenMap
 - array iterator: work in terms of BaseMap
 - fix clone to work on FrozenSet and FrozenVector
 - add Collection::is{Map|Vector|Set}Type to types.h to facilitate
   uses of Base{Map|Vector|Set}:: functionality
 - create collectionInitSet to distinguish keyed sets in literals
   (usable for FrozenMap) from keyed sets in mutations
 - add support for Frozen collections to compiler's ExpressionList::setCollectionType

Reviewed By: @paroski

Differential Revision: D1119583
2014-01-09 11:13:56 -08:00
Eugene Letuchy d7b4ed0ece collections: make StableMap and Map ==-comparable (using unordered Map equality)
... by forwarding $collection == $object to collectionEquals,
 even when $collection and $object are not the exact same class.

 This might set up the ability to also make Collection and
 FrozenCollection inter-comparable.

Reviewed By: @paroski

Differential Revision: D1116829
2014-01-09 11:13:52 -08:00
Eugene Letuchy bcdfa62d62 idl files: use | instead of _ for namespaces
_ is the one and only non-alphanumeric character that can
 show up in valid PHP classnames. Switch to | (or another character)
 should allow idl files to define classes containing _'s. We haven't
 hit this issue yet, but only as the result of classes such as
 `PHP_Unserializable_Class` happening to be defined in systemlib.php
 as opposed to idl files

Reviewed By: @jdelong

Differential Revision: D1116701
2014-01-09 11:13:48 -08:00
Jordan DeLong 0d04e63200 Initial hhbbc support for inferring private property types
To implement this, the member instruction support needed to
be beefed up a fair bit, and support was needed for scheduling whole
classes at a time in whole program mode.  Checking it in disabled;
it's still a work in progress.

Reviewed By: @dariorussi

Differential Revision: D1115782
2014-01-09 11:13:44 -08:00
Paul Tarjan f52716b149 stop forcing some tests to bad
Our test infra has changed so much, lets see how these do

Reviewed By: @alexmalyshev

Differential Revision: D1116573
2014-01-09 11:13:40 -08:00
Paul Tarjan d6cff51de1 delete some functions
`function_exists` returning false is better than throwing

Closes #1512

Reviewed By: @scannell

Differential Revision: D1118722
2014-01-09 11:13:35 -08:00
Paul Tarjan 61a840dd92 remove v infront of version number
It looks weird for the nightlies. I currently have

  HipHop VM vnightly-2014-01-06 (rel)
  Compiler: heads/master-0-g708d7c03f394d0fe537021161f7b5eff5497edbe
  Repo schema: 4f6cadf45ef19259e958e2796ca894f6df7b6db9

Reviewed By: @jdelong

Differential Revision: D1117594
2014-01-09 11:13:32 -08:00
Guilherme Ottoni beefa9ae21 Fix race in bindJmp service request
There's was an old race in the bindJmp service request, where a
translation gets invalidated while we're trying to bind a jump to it.
This was exposed by the region JIT, but it can also happen in sandbox
mode.

Reviewed By: @markw65

Differential Revision: D1118962
2014-01-09 11:13:27 -08:00
Owen Yamauchi fa82eb96ea Fix ARM mode, part 3: disable PGO, SetL issues
PGO mode isn't implemented in ARM mode. It's nontrivial to implement,
and I want to get the contbuild re-enabled as soon as possible so I'm
just turning off PGO in ARM mode for now.

Additionally, a test was failing because of another interp-one problem
with SetL, where we were trying to box an Uncounted. I added the logic
that boxing an Uninit promotes to InitNull.

Reviewed By: @ottoni

Differential Revision: D1118876
2014-01-09 11:13:23 -08:00
Bert Maher 40a8c7016f AHot size is 0 if it is unallocated
Trying to get vm-tcspace from the admin port of a sandbox
server crashes the VM, because AHot isn't allocated.  Just return 0 in
this case.

Reviewed By: @ottoni

Differential Revision: D1118505
2014-01-09 11:13:19 -08:00
Ori Livneh e49a9f8230 Fix RDTSC calibration in ext_hotprofiler
Do a busy loop instead of usleep(5000), since usleep(5000)
causes the CPU to halt, giving meaningless results.

Originally submitted by Tim Starling as pull request #65 for
preinheimer/xhprof.

Closes #1488

Reviewed By: @mikemag

Differential Revision: D1118168

Pulled By: @scannell
2014-01-09 11:13:15 -08:00
Sean Cannella 82e7a6ddc9 Revert "Turn on Region JIT with profile-guided traces"
This reverts commit 18da4c1a84e4678fe7d83b8272b0449c7dbbdd74.

Reviewed By: @ptarjan

Differential Revision: D1118688
2014-01-09 11:13:10 -08:00
Sean Cannella 802e93f6d1 Merge pull request #1520 from alexmalyshev/master
Add CMake support for using clang++ as the C++ compiler
2014-01-08 17:33:11 -08:00
Alexander Malyshev 162f859e83 Add CMake support for using clang++ as the C++ compiler
There was a weird issue where CHECK_CXX_SOURCE_COMPILES wouldn't find
clock_gettime under clang++, switching to CHECK_FUNCTION_EXISTS worked
both under clang++ and g++ on Ubuntu 13.10
2014-01-08 17:09:39 -08:00
Sean Canella 86db8b953c Fix compatibility.cpp/.h for non-Linux
Reviewed By: @ptarjan

Differential Revision: D1119787
2014-01-07 18:22:14 -08:00
Owen Yamauchi 278fc10f2a Fix ARM mode, part 2: DCE
Broken by D1109820. When eliminating the branch from an unguarded load,
and it's the last instruction in its block, we have to add a jump after
it so that the last instruction in the block "isBlockEnd".

Reviewed By: @edwinsmith

Differential Revision: D1117803
2014-01-07 10:39:33 -08:00
Owen Yamauchi 1edcf08d41 Fix ARM mode part 1: spill-stack
This got broken by D1107251. Time to just "implement" ("copy") cgStore
from the x64 backend for real, instead of just a few paths that I think
are important.

Reviewed By: @edwinsmith

Differential Revision: D1117398
2014-01-07 10:39:33 -08:00
Sean Cannella b0fddcb4db Update NEWS for "Beastie Boys"
Update NEWS for release

Reviewed By: @edwinsmith

Differential Revision: D1118494
2014-01-07 10:39:33 -08:00
Scott MacVicar 95f96e7287 Fix libxml_disable_entity_loader()
This wasn't calling requestInit and setting the libxml handler no null.
So the first time an error came along it would reset the handler from
no-op to reading again.

This is a much better fix, we set our custom handler in requestInit and
when libxml_disable_entity_loader we store that state as a member bool
ensuring requestInit is always called to set our own handler.

If the handler isn't inserted then the behavious is as before. The only
time this could go pear shaped is say we wanted to make the default be
off. In that case we'd need a global requestInit that is always called
since there are libxml references everywhere.

Reviewed By: @jdelong

Differential Revision: D1116686
2014-01-07 10:39:32 -08:00
Paul Tarjan 8a2b1f7905 change 404 page to list paths
Many people are having trouble with the open source build getting a "Not Found" message and not knowing what to do from there. What do you think about showing the paths we tried? If you set `RuntimeOption::ErrorDocument404` then that will be used instead.

Reviewed By: @scannell

Differential Revision: D1109693
2014-01-07 10:39:32 -08:00
Joseph Marrama d629f22d6d Fixed the import script in ext_zend_compat
The import.php script called a non-existant method 'getSubpath'
on a FileInfo object. This commit fixes it so it now works. I verified
this works importing a new extension with multiple source files in
nested directories.

Closes #1509

Reviewed By: @ptarjan

Differential Revision: D1118180

Pulled By: @scannell
2014-01-07 10:39:32 -08:00
Jan Oravec a9a72ec46c Fix memory leak in Gen{Map,Vector}WaitHandle
The code assumed obj->clone() function to return an ObjectData* with
zero refcount, but the refcount is initialized to 1 by clone().

Let's attach() this already refcounted ObjectData* to the Object.

Reviewed By: @jdelong

Differential Revision: D1117583
2014-01-07 10:39:31 -08:00
Jordan DeLong bf8736b06c Replace mapInsertUnique with checks of .second
Reviewed By: @markw65

Differential Revision: D1116397
2014-01-07 10:39:31 -08:00
Jordan DeLong 74a78e4322 Move util/base.h to util/deprecated for remaining users
Most of the remaining stuff under hphp/compiler that gets it
from hphp/compiler/hphp.h

Reviewed By: @markw65

Differential Revision: D1115344
2014-01-07 10:39:31 -08:00
Jordan DeLong 6fb82db7ab Fatal on eval in RepoAuthoritative mode
Reviewed By: @ptarjan

Differential Revision: D1116204
2014-01-07 10:39:30 -08:00
Jordan DeLong 5db636ae70 Stop unit tests from doing eval() in repo mode
Most of these tests were only about eval, so they get norepo.
For FPassC, I pulled the eval case into its own test.  This is
separate from the diff to actual make eval fatal in RepoAuthoritative
in case we end up needing to revert that one ...

Reviewed By: @scannell

Differential Revision: D1116200
2014-01-07 10:39:30 -08:00
Elliot Lynde 29b90f97be Add ReflectionFunctionAbstract::isAsync
See attached task. We want to kill mockYield but need to be able tell if a function is async.

Reviewed By: @jano

Differential Revision: D1110027
2014-01-07 10:39:29 -08:00
Guilherme Ottoni 7e61c7e09c Turn on Region JIT with profile-guided traces
This diff turns on the initial version of the region JIT, with
"hottrace" regions.  To contain profiling and retranslation overheads,
the region JIT only targets functions marked as hot for now.  Compared
to the tracelet JIT, CPU time is in the noise according to perflab and
production testing. The region translator still has performance
issues, both known (e.g. guard relaxation is still disabled) and
unknown (translateRegion with tracelet regions still produces worse
code than translateTracelet, even with guard relaxation out of the
picture), and we'll continue to work on these.  Once we address these
issues, and try other ideas that the region JIT enables, we should
start seeing performance gains.  Nevertheless, we feel like the
current state is good enough to push the region JIT to release.  So,
if no one has any objection, we'd like to turn on the region JIT and
try to get it in the next release.

Reviewed By: @bertmaher

Differential Revision: D1116793
2014-01-07 10:39:29 -08:00
Kristaps Kaupe 01e6a895ea Libdwarf 20130729 (and later) support
Libdwarf 20130729 not only has changed Dwarf_Callback_Func_c
definition, but also adds two new functions dwarf_encode_leb128 and
dwarf_encode_signed_leb128. So, we can check for a presence of symbol in
a library, to distinguish between the old and new libdwarf.

Closes #1490

Reviewed By: @ptarjan

Differential Revision: D1117070

Pulled By: @scannell
2014-01-07 10:39:23 -08:00
Alexander 35c9784c6e PDOException should have a property "errorInfo"
Added two tests, one to verify the property exists, another one to
verify that the extra error info is actually set.

Closes #1412
Closes #1498

Reviewed By: @ptarjan

Differential Revision: D1117082

Pulled By: @scannell
2014-01-07 10:16:54 -08:00
Alexander a9a2737ac5 DateTime::createFromFormat() return FALSE on error
DateTime::createFromFormat() should return false on failure.

Closes #1495
Closes #1497

Reviewed By: @ptarjan

Differential Revision: D1117091

Pulled By: @scannell
2014-01-07 10:16:50 -08:00
Paul Tarjan 0b5fd84276 import tests that used to spew
this is so awesome that these work

Reviewed By: @scannell

Differential Revision: D1116552
2014-01-07 10:16:46 -08:00
Eugene Letuchy f773f87f7b check trait requirements during flattening
In repo mode, traits are flattened into the preClasses of using
 classes. After {D1111932}, there's no attempt made to import traits
 at class instantiation time (in repo mode), so the checks of trait
 requirements were not done. This diff patches up that hole, with the
 (small) limitation of not quite tracking the chain of
 trait-using-trait usages in error messages.

Reviewed By: @markw65

Differential Revision: D1116296
2014-01-07 10:16:39 -08:00
Eugene Letuchy a1d2e230bc skip trait import in repo mode
In repo mode, we've already done whole program analysis and
 imported trait methods, properties, and interfaces into the
 containing preclass. It doesn't make sense to redo that work when
 instantiating Class*s.

 The downstream effects of this change in repo mode are:
  - reflection should get (marginally) faster: no work for trait alias
    rules until the first time they're reflected upon
  - "used traits" reflection uses preclasses only, except for the case
    of object prop iteration, which continues to use the list of trait
    classes and works as before, but better (outside of repo mode,
    trait props are used ; in repo mode, trait props are ignored as
    redundant)
  - less work at warmup (doing nothing is faster than doing something
    for each trait method)
  - trait requirements are not enforced (left for followup diff)

Reviewed By: @markw65

Differential Revision: D1111932
2014-01-07 10:16:36 -08:00
Eugene Letuchy 9d7f144ac8 removed unnecessary subdirectories in test/slow/hh_namespace_migration
test/slow/hh_namespace_migration/redundant/redundant1.php is not useful

Reviewed By: @jdelong

Differential Revision: D1116835
2014-01-07 10:16:32 -08:00
Sean Cannella 270d5dfb57 Implement support for binary-number syntax
Implements support for binary number syntax ("0b10")

Closes #1425
Closes #1454

Reviewed By: @jdelong

Differential Revision: D1114405
2014-01-07 10:16:26 -08:00
Philippe Ajoux 5100923fea Add child argument to AsyncFunctionWaitHandle::onCreate callback.
An AsyncFunctionWaitHandle is only created when an object it `await`s is blocking. Currently these `await` events trigger the `onAwait()` callback. However, the first time an async function awaits is also the first time it actually gets created. Thus, the first actual `await` results in the `onCreate()` callback. This is fine, but right now there is no way to know what `WaitHandle` caused the creation of the AsyncFunctionWaitHandle. This useful to know.

For example, the current implementation of Teak does not, from my experimentation, get the call stack correct because it assumes that `asio_get_current()` is the parent when the `onCreate()` callback is called. However, this is not true. With the addition of the child that caused the creation, this can be fixed.

Reviewed By: @jano

Differential Revision: D1115761
2014-01-07 10:11:52 -08:00
Manish Bajaj e30a20175c Setting a boolean flag in getTyped
Timezone passed is null and doesn't match the class, so exception is thrown.

Reviewed By: @ptarjan

Differential Revision: D1113303
2014-01-07 10:11:48 -08:00
Bert Maher b7f6af03d8 Get rid of unnecessary includes of unit.h
It's pretty big, and it looks like a few of the places it's
included don't actually need it.

Reviewed By: @jdelong

Differential Revision: D1116020
2014-01-07 10:11:44 -08:00
mwilliams 3f867d5b27 Catch jmp/call to zero at translation time
Its much easier to catch such bugs at translation time,
than after we crash with $rip == 0.

Reviewed By: @edwinsmith

Differential Revision: D1114185
2014-01-07 10:11:40 -08:00
Bert Maher b62db208b7 Make expected output of setprofile-this more permissive with paths
This test fails when I run it in repo mode from hphp/, and it
just looks like the expectf pattern is too strict.

Reviewed By: @ptarjan

Differential Revision: D1116012
2014-01-07 10:11:33 -08:00
Sara Golemon a94542e548 Add -mcrc32 to CXX_FLAGS
Fixed build on gcc >= 4.8
2014-01-06 19:02:16 -08:00
Louis Kruger df44326811 Allow ReflectionFunction::getDefaultValue() on some builtin functions
Allow getDefaultValue() to be called on a ReflectionFunction in certain cases (where the default value can be deserialized from the IDL)

Reviewed By: @ptarjan

Differential Revision: D1116436
2014-01-06 11:42:48 -08:00
Behnam Esfahbod 2b6466e70e Use array_merge instead of plus operator
Use array_merge() instead of plus (`+`) operator. Also, add new test file for
the hMSet/hMGet pair of functions/commands.

Working on #3340180, we realized that we do not have any .expect file for the test files in `hphp/test/slow/ext_redis/` so noone is actually able to test the module (besides the fact that we don't have any automated slow-test working since no Redis server is setup during test).

Based on what I can see, most of the tests are working alright right now, but:

1. Redis commands HMSET/HMGET do not have any test files, and looks like HMGET is actually broken, besides the syntax issue mentioned in #3340180.

2. Most test files are looking for obvious cases, but not exceptional cases like non-existing lookup keys.

Reviewed By: @ptarjan

Differential Revision: D1108114
2014-01-06 11:42:48 -08:00
Edwin Smith b48b4e3217 Simplify B|NF flags to B.
NF means No Flag, I should have removed them when adding B.

Reviewed By: @jdelong

Differential Revision: D1116856
2014-01-06 11:42:47 -08:00
Edwin Smith 8c43d7d052 XLS: Use vectors instead of lists for ranges and use-positions
lists are inefficient for the way we use these, vectors are smaller and faster,
enable binary searching (future), and typically short anyway.

Reviewed By: @jdelong

Differential Revision: D1116766
2014-01-06 11:42:47 -08:00
Sara Golemon 3222f6fc15 Add missing includes for OSS build
The removal of base.h includes left some missing
headers scattered around, mostly in util.

Reviewed By: @jdelong

Differential Revision: D1117195
2014-01-06 11:42:36 -08:00
Jordan DeLong 74b1dccab4 Remove base.h includes from runtime/, fix up indirect dependencies
This probably just pushes a bit of it down to
runtime/base/types.h, but at least a few decent-sized includes are out
of every TU now (lexical_cast.hpp, iostream, boost/foreach, and
filesystem.hpp).  Haven't measured impact on build times if any.

Reviewed By: @edwinsmith

Differential Revision: D1115343
2014-01-06 11:42:22 -08:00
Jordan DeLong 0a0712262e Remove #includes of base.h from the headers in util/
And try to fix downstream indirect dependencies to include
what they use (plenty of indirect includes still missing, though).
Most TU's still get this all via the complex-types.h stuff.

Reviewed By: @dariorussi

Differential Revision: D1115342
2014-01-06 11:42:21 -08:00
Jordan DeLong de03fa1f5d Move util/json.h to compiler
It references compiler-specific types like AnalysisResult.
Replace the one live use of the JSON::Escape function from this header
in the runtime with folly call; other use is about to be removed in
another diff from dario.

Reviewed By: @dariorussi

Differential Revision: D1115340
2014-01-06 11:42:20 -08:00
Jordan DeLong 5ba020d800 Move small function objects to their own header.
Reviewed By: @edwinsmith

Differential Revision: D1114045
2014-01-06 11:42:20 -08:00
Jordan DeLong e1631211ad Remove typedef unsigned char uchar
Reviewed By: @edwinsmith

Differential Revision: D1114044
2014-01-06 11:42:19 -08:00
Jordan DeLong 8bbbe52328 Remove dependencies on util/base.h for map helpers
Just use count() for the fooContains ones, mapInsert didn't
do anything, move mapInsertUnique to its only user, use folly's
MapUtil.h versions instead for the other ones.

Reviewed By: @markw65

Differential Revision: D1114043
2014-01-06 11:42:19 -08:00
Jordan DeLong e7f6aa501c Remove some unused, single-use, or excessively trivial helpers
A couple of these are only trivial-seeming because now we
have range-based for or lambdas.

Reviewed By: @markw65

Differential Revision: D1114042
2014-01-06 11:42:18 -08:00
Jordan DeLong 44e0efe2a8 Move hphpiCompat to its only remaining use site
Reviewed By: @markw65

Differential Revision: D1114041
2014-01-06 11:42:18 -08:00
Jordan DeLong 71ae9fbb30 Move safe_cast out into its own header
Reviewed By: @dariorussi

Differential Revision: D1114040
2014-01-06 11:42:18 -08:00
Jordan DeLong 6b411c6072 Remove a few typedefs for stl combinations from util/base.h
Reviewed By: @dariorussi

Differential Revision: D1114039
2014-01-06 11:42:17 -08:00
Jordan DeLong 0418b65a11 Delete some shared_ptr<FILE> stuff
FilePtr seemed strange to define in base.h.  Turned out only
process.cpp uses it.  FileReader at first seemed to be freeing FILE*'s
with delete, but it turned out the instance version of it was dead
code, and the class was really just a function.  The other site was
supposed to be a scope guard.

Reviewed By: @dariorussi

Differential Revision: D1114038
2014-01-06 11:42:17 -08:00
Jordan DeLong 3b1120f190 Deprecate DECLARE_BOOST_TYPES, remove uses outside hphp/compiler
Reviewed By: @markw65

Differential Revision: D1114037
2014-01-06 11:42:16 -08:00
Jordan DeLong 758dbc6cbb Move the hphp_hash_* typedefs to their own header
Reviewed By: @ptarjan

Differential Revision: D1114036
2014-01-06 11:42:16 -08:00
Jordan DeLong e44fab1e77 Don't specialize std::hash for char* in base.h
At least one call site may have been using the custom hash
inadvertently with AtomicHashMap but I preserved the behavior.

It seems like this is a little too dangerous, too.  If any translation
unit in the program uses std::hash<char*> without first including
base.h, we have undefined behavior.  Since we don't control a lot of
the code linked into our binary this seems like a bad idea.

(Plus it's just nicer to be explicit about whether a char* key is
being treated as just a pointer or as a C-style string at a use site
so you can tell what is going on.)

Reviewed By: @edwinsmith

Differential Revision: D1114035
2014-01-06 11:42:15 -08:00
Jordan DeLong 1050dfe523 Don't include via datatype.h or via hphp-value.h
Right now, through this route (among others), nearly every
translation unit in the runtime includes
boost/interprocess/sync/interprocess_upgradable_mutex.hpp ... just in
case you might want to use it.

This diff doesn't solve the problem, it's just a start (all the other
sub-headers for complex-types.h do this same stuff right now).

Reviewed By: @edwinsmith

Differential Revision: D1114034
2014-01-06 11:42:15 -08:00
Edwin Smith ff2d01de93 Prepare for enabling XLS register allocator.
Disable SIMD registers when using packed_tv.

Reviewed By: @jdelong

Differential Revision: D1102996
2014-01-06 11:42:15 -08:00
Edwin Smith 6d10ad646a JmpSwitchDest has no destination tmp.
Fix ir.specification

Reviewed By: @jdelong

Differential Revision: D1116836
2014-01-06 11:42:14 -08:00
Sara Golemon 5454d1e028 Update folly 2014-01-06 11:42:14 -08:00
Sara Golemon 708d7c03f3 Move ext/sockets constants from constants.idl.json to ext_sockets.cpp
Organizationally makes more sense.

Also allows us to set the constant values based on the system defines
rather than hard-coded posix values, and make some conditionally
available constants conditional.

I went through php-src/ext/sockets/sockets.c to match PHP:

Newly added sockets constants:
MSG_CTRUNC
MSG_TRUNC
IP_MULTICAST_IF
IP_MULTICAST_TTL
IP_MULTICAST_LOOP
IPV6_MULTICAST_IF
IPV6_MULTICAST_HOPS
IPV6_MULTICAST_LOOP
IPPROTO_IP
IPPROTO_IPV6
IPV6_UNICAST_HOPS

Existing constants made conditional:
MSG_EOR
MSG_EOF

Newly added conditional constants:
MSG_CONFIRM
MSG_ERRQUEUE
MSG_NOSIGNAL
MSG_DONTWAIT
MSG_MORE
MSG_WAITFORONE
MSG_CMSG_CLOEXEC
SO_REUSEPORT
SO_FAMILY
SO_BINDTODEVICE
TCP_NODELAY

Note: I left out the MCAST_* constants in ext/sockets because
we don't actually have the code to do anything with them.
We can add those in a separate diff.

Reviewed By: @jdelong

Differential Revision: D1116722
2014-01-05 08:59:36 -08:00
Eugene Letuchy b368db8f3e collections: centralize equality in BaseMap
We'll most likely stay with Map's equality semantics for ==,
 but StableMap's equality semantics will likely have a place as a
 user-PHP accessible method on collections.

Reviewed By: @jdelong

Differential Revision: D1116700
2014-01-05 08:59:33 -08:00
Eugene Letuchy 80cffcc72f collections: introduce BaseMap superclass for Map and StableMap
This diff ensures that Map and StableMap have the same
 storage implementation in preparation for:

  - StableMap going away (except, perhaps, for its equality semantics)
  - FrozenMap coming into existence

 Specifically, this diff:

  - introduces a BaseMap superclass
  - makes c_Map inherit from BaseMap
    - renames c_Map::t_xyz to BaseMap::php_xyz
    - make c_Map::t_xyz a thin wrapper over BaseMap::php_xyz
  - makes c_StableMap inherit from BaseMap
    - removes vast majority of old implementation
    - adds c_StableMap::t_xyz as a thin wrapper over BaseMap::php_xyz
    - keeps c_StableMap::equals behavior (order mattering)
    - keeps unserialization behavior (serialize to 'StableMap' class)
  - gets rid of StableMapIterator in favor of a transformed MapIterator that works with any BaseMap

 Apologies to reviewers: this started out as a diff series with
 StableMap extends Map to verify limited number of test failures, and
 git code move detecting wasn't quite good enough to make commit
 rewriting less painful.

Reviewed By: @jdelong

Differential Revision: D1113840
2014-01-05 08:59:30 -08:00
Eugene Letuchy 3f304a7aee collections: macrofy materialization and magic-method declarations ...
... as a direct counterpart to similar macros in the .cpp file

Reviewed By: @jdelong

Differential Revision: D1116696
2014-01-05 08:59:26 -08:00
Edwin Smith 5d2da8095c Fix broken cycle detection in doRegMoves()
It failed to detect a cycle if the path to the cycle started
from a leaf node that wasn't in the cycle.  This diff goes
back to the old algorithm, adapted for PhysReg and PhysReg::Map,
and also goes back to fixed-length arrays to avoid allocations.

Reviewed By: @jdelong

Differential Revision: D1116541
2014-01-05 08:59:23 -08:00
Eugene Letuchy 3b7e172be5 collections: support sorting of Maps
Now that Maps retain insertion order and have an internal
 representation similar to arrays, there's no reason not to implement
 sorting on them. The implementations are largely copy-pasta

Reviewed By: @jdelong

Differential Revision: D1113839
2014-01-05 08:55:50 -08:00
Paul Tarjan 0b8bec7835 import segfaulting tests
The test runner is now much more resiliant than it used to be, so it can endure a segfault or two. Having the tests is better than not.

Reviewed By: @jdelong

Differential Revision: D1116517
2014-01-05 08:55:49 -08:00
Liu Yang bdeab11496 Adding ENT_IGNORE
ENT_IGNORE is added, which will silently discard invalid code unit sequences instead of returning an empty string.
I changed relevant QuoteStyle matching to flag bitmask checking. I kept our previous QuoteStyle method since it's used in many other places.

Reviewed By: @ptarjan

Differential Revision: D1116336
2014-01-05 08:55:49 -08:00
Paul Tarjan 75922a20ca import many tests that used to hang forever
You have no idea how happy this makes me. We are down to 5 perma-hanging tests.

Reviewed By: @JoelMarcey

Differential Revision: D1116535
2014-01-05 08:55:49 -08:00
Paul Tarjan dd4ddd5ee0 re-enable ftp_chmod_basic
The other ftp tests have ben fine since I fixed the port choosing issue upstream.

Reviewed By: @jdelong

Differential Revision: D1116504
2014-01-05 08:55:48 -08:00
Jordan DeLong c3a9cea640 Fix bad_ini_quotes test
Oops.

Reviewed By: @ptarjan

Differential Revision: D1116602
2014-01-05 08:55:48 -08:00
Eugene Letuchy 11bd030e66 emit fatal bytecodes from errors found during trait flattening
An overtly literal person might suspect that ##Compiler::Error## would
involve a compiler spitting out an error message reflected in the
ensuing code. Instead, it turns out that it records the message in a
separate area and blithely **continues onwards** as if the error never
occurred.

In repo mode, traits are imported in the compiler as opposed to at
Class initiation time. My contention is that any fatals/errors
discored during trait flattening should be available at runtime when
an attempt is made to load the file.

This diff introduces the notion of an `AnalysisTimeFatal` to the
compiler and ensures that this fatal propagates (with [analysis] added
to the fatal message). It also ensures that trait flattening and
non-repo trait import share the same error messages, which should make
it possible to eventually stop producing ##.expectf## files that
contain the almost entirely inscrutable ##HPHP Fatal Error: %s##.

Reviewed By: @markw65

Differential Revision: D1112629
2014-01-05 08:55:47 -08:00
Jordan DeLong ac8474cbe9 Add a unit test that aborts with recent ini changes
So that we can test this case before adding it back.

Reviewed By: @ptarjan

Differential Revision: D1116203
2014-01-05 08:55:47 -08:00
Jordan DeLong 8ebc0e6702 Revert "Fixes to parse_ini_(file|string)"
This reverts commit 0d694bcf6c0fa7aa4c15f166d0732ea37c5566d8.
It's causing parse_ini_string to sometimes hit assertions in
StringData::setSize, and behavior issues on the intern tier.  The fix
wasn't completely obvious and there's an open diff relating to
relevant cases (escaped double quotes), so let's just revert until it
can be looked at by emil.

Reviewed By: @markw65

Differential Revision: D1116199
2014-01-05 08:55:47 -08:00
Jordan DeLong 5f2d1b25c4 Revert "INI parser fixes for OSS"
This is required to revert "Fixes to parse_ini_(file|string)"
cleanly.

Reviewed By: @markw65

Differential Revision: D1116195
2014-01-05 08:55:46 -08:00
Paul Tarjan 4620d7a132 delete FastCGIConnection object
This was a leak appearing in @apuckey's valgrind dump. @simpkins said the object should delete itself since either the success or error callbacks will for sure be called for each connection.

Closes #1252

Reviewed By: @scannell

Differential Revision: D1115399
2014-01-05 08:55:01 -08:00
Paul Tarjan 186c74e761 enable TestFastCGIProtocol
The Server tests were the flakey ones, but both got disabled. Lets leave the unit tests around so I don't break stuff.

Reviewed By: @scannell

Differential Revision: D1115879
2014-01-04 12:53:54 -08:00
Paul Tarjan 5fd5b01be3 fixup isDefaultValueAvailable() and isOptional() for builtins
The `Func*` doesn't keep around information about defaults from the IDL so I switched to using the `ClassInfo`. That in turn showed me there was some logic in there that wasn't being used by anything anymore (as there are no values in the IDL's with foo::bar() in them except for `TimeStamp::Current` which is clearly destined for C++). Ripping that out allowed me to kill a helper functions.

I then did the real work that I wanted and marked parameters with `internal` and don't say there is a default value for those and throw the same exception that zend does.

Reviewed By: @markw65

Differential Revision: D1054845
2014-01-04 12:53:51 -08:00
Zach Wasserman d302ddd725 Fixed xmlwriter null prefix bug
HPHP was inconsistent with Zend PHP in its rendering of the XMLWriter
startElementNS method. This diff brings better consistency with Zend for the
case of null prefix string or empty prefix string.

Reviewed By: @ptarjan

Differential Revision: D1114272
2014-01-04 12:53:47 -08:00
Eugene Letuchy 5cf6d04a90 add interfaces to whole program (repo mode) trait flattening
anietoro added the 'trait T implements I' syntax, but not support for it in repo mode.

Reviewed By: @markw65

Differential Revision: D1111927
2014-01-04 12:53:44 -08:00
Diego Giagio 5e8bc5a19e Add more stream_wrapper functions used in Drupal
According to some users, Drupal 7 uses public:// and
temporary:// to store and move files around by using stream_wrappers.
Some functions of stream_wrappers weren't implemented. This patch adds
the following missing functions:

unlink
rename
mkdir (recursive or not)
rmdir

Closes #1474

Reviewed By: @ptarjan

Differential Revision: D1115507

Pulled By: @scannell
2014-01-04 12:53:40 -08:00
Antony Puckey f0c74f27df Allow transport to override SERVER_ headers
Uses the following headers from the transport (for fastcgi)
instead of the local config if they exist:

SERVER_NAME
SERVER_ADDR
SERVER_PORT

Closes #1445

Reviewed By: @ptarjan

Differential Revision: D1114969

Pulled By: @scannell
2014-01-04 12:53:36 -08:00
Elliot Lynde 7236226b4a See if HasGeneratorAsBody is used
Sean thought maybe not since it's not clear where it's set

Reviewed By: @jano

Differential Revision: D1113304
2014-01-04 12:53:33 -08:00
Bert Maher 57e32a8985 Put demangled symbols in perf map
It's easier to read perf output with demangled symbols

Reviewed By: @markw65

Differential Revision: D1114722
2014-01-04 12:53:29 -08:00
Bert Maher 05a30a5ce4 Move isConvIntOrPtrToBool close to its one use
It's a single use function so make it a lambda close to the use

Reviewed By: @jdelong

Differential Revision: D1114902
2014-01-04 12:53:25 -08:00
Edwin Smith a6cebd362c Remove dead code in checkTmpsSpanningCalls()
Left over from the recent rewrite.

Reviewed By: @scannell

Differential Revision: D1115439
2014-01-04 12:53:21 -08:00
Dario Russi d8313742e1 Allow indirect calls via emitCall with CppCall support
Extend CppCall to support a call indirect (via register) style and implement a call to a Variant destructor via the indirect call instead of helper

Reviewed By: @ottoni

Differential Revision: D1090464
2014-01-04 12:53:18 -08:00
Daniel Sloof fe62948b58 fix stream_get_contents without specified offset
File does its own internal buffering and uses m_readpos, m_writepos,
m_position for the purpose of keeping track of file offsets. This means
that current (PHP) position is not in sync with the underlying file
descriptor (m_fd).

This works fine, were it not for the fact that ext_stream calls directly
into pure virtual method readImpl that generally lives in PlainFile
and works directly on the file descriptor that might contain an
invalid (buffered-ahead) position.

This pull request does several things:
- Remove default value 0 for File::read(int64_t length), since that
  implementation returns earlier for 0 values anyway.
- Implement an overloaded method File::read() that reads the remainder
  of the file (until EOF) by using proper File::m_* properties.
- Make ext_stream call into File::read instead of PlainFile::readImpl.

Closes #1333

Reviewed By: @ptarjan

Differential Revision: D1091550

Pulled By: @scannell
2014-01-04 12:53:14 -08:00
Benjamin Zikarsky bd636b9f39 Fixes "false" hashbang interpretation
- Lexer now only interprets "#!" as a line-1-hashbang
- Added tests for a leading line with both "#test" and a real hash-bang
like "#!hashbang"

Closes #1396
Closes #1465

Reviewed By: @ptarjan

Differential Revision: D1114361

Pulled By: @scannell
2014-01-04 12:53:13 -08:00
Guilherme Ottoni b8ca92a08c Don't emit type predictions in TransOptimize mode
I noticed that the region translator was emitting type checks for
values that were both predicted (via the interpreter type profiler)
and inferred (via the front-end).  This is a result of the type
profiler annotating the output of the instructions while the front-end
annotates the instruction inputs.  Therefore, we ended up generating a
CheckStk instruction and then an AssertStk instruction.  The AssertStk
instruction is then simplified away (since it's asserting a type that
is already known due to the previous CheckStk), and the CheckStk
remains. The tracelet translator avoids this problem by looking ahead
in the chain of NormalizedInstructions (via getOutputUsage) to
determine that the prediction is unecessary.

I PGO mode, we don't really need the values coming from the
interpreter type profiler.  TransProfile translations end whenever
there's a side-exit, and type predictions incur side-exits.  And when
we stitch multiple TransProfile translations together to for a
hottrace region (in TransOptimize mode), the guard for the top of the
stack essentially does the role of type prediction.  And, if the value
is also inferred, then the guard is omitted and the AssertStk is
emitted and not eliminated (since there's not previous CheckStk).

Note that this diff only solves the problem for regions formed via PGO
(hottrace only).  Fixing the problem for other region selectors is
going to be more involved and I tasked to do it separately.

Reviewed By: @swtaarrs

Differential Revision: D1112059
2014-01-02 20:05:07 -08:00
Sean Cannella 142c8dc839 Fix spurious conversion notice in method_exists
Arrays can't possibly pass a method/class check as they convert
to array (a reserved keyword) so don't bother toString-ing in that case.

Closes #1475

Reviewed By: @ptarjan

Differential Revision: D1114192
2014-01-02 20:05:04 -08:00
javer efaf782ccc Fix memory leak in pdo_parse_params
Fixed memory leak after executing PDOStatement::execute() with bound parameters. Also removed unnecessary copying of result query string.

Test case (I don't know whether it can be tested with Travis because it requires MySQL connection):

<?php
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root', '');
$data = str_repeat('a', 1000000);

for ($n = 0; $n < 50; $n++) {
    $stmt = $pdo->prepare('SELECT :data = 1');
    $stmt->bindValue(':data', $data);
    $stmt->execute();
    $stmt = null;
    echo sprintf("%dM\n", memory_get_usage(true) / 1048576);
}

Closes #1459

Reviewed By: @ptarjan

Differential Revision: D1113187

Pulled By: @scannell
2014-01-02 20:05:01 -08:00
javer a02ae44cd4 apc_inc/dec should return false on failure
Return false instead of 0 when failure occured while calling
apc_inc or apc_dec.

Closes #1472
Closes #1473

Reviewed By: @dariorussi

Differential Revision: D1114169

Pulled By: @scannell
2014-01-02 20:04:57 -08:00
Jordan DeLong 2c7fcd7ba3 If HttpServer can't bind ports, go directly to _Exit(1)
Apparently this code was just returning while leaving a bunch
of threads running, which is pretty bad.

Reviewed By: @markw65

Differential Revision: D1111881
2014-01-02 20:04:54 -08:00
Dominic Luechinger 971a4c35cd In FastCGI the server address could not be set
Due to a bug in the FastCGI server the start up of the server with
a specific IP address was not possible.
Example:
hhvm --config /etc/hhvm/server.hdf -m server -vServer.Type=fastcgi -vServer.IP=127.0.0.1 -vServer.Port=9100

Before bugfix:

netstat -tulpen|grep 9100
> tcp6       0      0 :::9100                 :::*                    LISTEN
After bugfix:

netstat -tulpen|grep 9100
> tcp        0      0 127.0.0.1:9100          0.0.0.0:*               LISTEN

Closes #1467

Reviewed By: @ptarjan

Differential Revision: D1114159

Pulled By: @scannell
2014-01-02 20:04:51 -08:00
Brandon Wamboldt 1161d81be3 Fix preg_quote not escaping dashes
Fix preg_quote not escaping dashes

Closes #1440
Closes #1441

Reviewed By: @elgenie

Differential Revision: D1111976

Pulled By: @scannell
2014-01-02 20:04:47 -08:00
Jim Radford b87deae51e VirtualHost.<name>.Pattern matches host not paths
This allows Patterns with a leading ^ to match.

Pattern ^www.example.com$

Closes #1463

Reviewed By: @markw65

Differential Revision: D1114114

Pulled By: @scannell
2014-01-02 20:04:44 -08:00
Edwin Smith 212f4a726d Remove TakeStack instructions after optimizeRefcounts()
They are essentially Nops, inserted to preserve information
from the simplify pass.  They aren't needed anymore after
refcount optimizations; convert them to Nop so dce cleans
them up.

Reviewed By: @swtaarrs

Differential Revision: D1114262
2014-01-02 20:04:40 -08:00
Edwin Smith d5a96369ac Strengthen checkTmpsSpanningCalls()
Replace preorder walk over dom tree with bottom-up postorder walk,
and merge state along edges.  This catches more violations.
Also, add ContEnter, ignore TakeStack, and StkPtr-typed tmps.

Reviewed By: @swtaarrs

Differential Revision: D1114191
2014-01-02 20:04:37 -08:00
Jordan DeLong 88389ab7d8 Minor refactor of how non-constant hhbbc options are set
The only option that's actually runtime settable right now is
the list of fb_intercept-able functions.  I'm going to want more of
these soon, but the way it was set up was slightly annoying.

This isn't great still---it just moves the place we propagate options
closer to compiler_main.  We don't want these options to actually
exist in Compiler::Option because otherwise we'd have to merge
libhhbbc.a with libhphp_analysis.a, and they don't really fit in
RuntimeOption either.  (Eventually I'd like to just have another
main() for hhbbc with its own option parser---this would also make it
easy to repeatedly run hhbbc on a repo while developing, without
redoing the rest of the production build.)

Reviewed By: @dariorussi

Differential Revision: D1113886
2014-01-02 20:04:33 -08:00
Bert Maher b0d11cf284 Use PRId64 instead of ld for uint64_t
Building on OSX warns about ld

Reviewed By: @edwinsmith

Differential Revision: D1109785
2014-01-02 20:04:30 -08:00
Bert Maher 9852392fe1 Don't redefine ENABLE_GD_TTF if defined
Squashes a warning when building on OSX

Reviewed By: @ptarjan

Differential Revision: D1109786
2014-01-02 20:04:26 -08:00
mwilliams 9a29b5d027 Slightly better code gen in a couple of places
I noticed while debugging a production crash that

  testq -1, MemRef

is 3 bytes bigger than

  cmpq 0, MemRef

and is typically interchangable.

While looking for test*s to change, I noticed that we always
do ConvObjToBool, even when we know the Class statically, and know
that the result is going to be true. So added a case to the simplifier.

Reviewed By: @elgenie

Differential Revision: D1109374
2014-01-02 20:04:23 -08:00
Jordan DeLong a78e186d54 Fix a reference counting bug in emitFPushCufOp
If you have a non-persistent class in this code path, we
generate code that fails the reference count validator.  It IncRefs
the $this pointer before generating the conditional branch to the exit
trace for the class not being defined.

Reviewed By: @edwinsmith

Differential Revision: D1113826
2014-01-02 20:04:19 -08:00
Eugene Letuchy a836bb0f86 boost::{enable|disable}_if_c => std::enable_if
apparently std::enable_if is the new C++11 hotness

Reviewed By: @alexmalyshev

Differential Revision: D1112652
2014-01-02 20:04:09 -08:00
Chengyan Fu 7c29a08796 revert some unesessary change in D1110769
I revert some change will block my task in coldstage which
be brought into the master by arc land. This diff is to revert that
and local changes.

Reviewed By: @ptarjan

Differential Revision: D1113815
2014-01-02 20:04:05 -08:00
Chengyan Fu e0de978c02 Fix Curl Upload Failure
hhvm will callback the compiled php read function to parse the
file to be uploaded. During this process, a file instead of a file
descriptor id should be passed into the hphp VM.
The error is caused by sending file->fb() rather than file itself into
the callback function. The actual hphp fread library try to make a dummy
resource after receiving an integer when a ResourceData is excepted.
The dummy resource file then causes a bunch of error which ends up in
the "read function returned funny value".

Reviewed By: @ptarjan

Differential Revision: D1110769
2014-01-02 20:04:02 -08:00
Sara Golemon 93d0137393 Prune dead code from compiler/option
Came across this option while cleaning up HPHP_HOME,
looks to be completely dead.

Reviewed By: @ptarjan

Differential Revision: D1111937
2014-01-02 20:03:58 -08:00
Sean Cannella 78929051ef hhprof should only collect profiles when profiling
HHProf should only collect profiles when profiling instead of
proactively and then only reporting when profiling as this incurs a huge
amount of runtime overhead by default with the runtime option enabled.

Reviewed By: @dariorussi

Differential Revision: D1112865
2014-01-02 20:03:54 -08:00
Brandon Wamboldt bf73fae1f2 Already declared constants should cause a notice
Zend will throw a PHP Notice if you try to re-declare a
constant that has already been declared, but HipHop was throwing a PHP
Warning.

Closes #1456

Reviewed By: @jdelong

Differential Revision: D1112973

Pulled By: @scannell
2014-01-02 20:03:50 -08:00
Sara Golemon 39416ccbdc Run a double-quoted json scalar string through the parser
The non-JSON fallback for quoted string values
should still respect JSON string encoding rules like
unicode, and printf-style escape sequences.

Reviewed By: @scannell

Differential Revision: D1112801
2013-12-30 12:05:06 -08:00
Sara Golemon 370b2b8cb2 Clean json_last_error() when parsing non-objects
JSON_parse() regards scalars as a syntax error,
but we have explicit checks for null, true, false,
numerics, and strings.  Clear the error when we return these.

Reviewed By: @scannell

Differential Revision: D1112796
2013-12-30 12:05:03 -08:00
Dario Russi a8dbb3b8ad Separate bits for "non ref count" and "static" types.
Use different bits for static type and ref counted types. Every static type is not ref counted however we want to introduce the concept of a non static type that does not need ref counting.

Reviewed By: @markw65

Differential Revision: D1090994
2013-12-30 12:05:00 -08:00
Dario Russi 89e54f5186 Change hasInternalReference to DataWalker and track more info of the object graph
Change, centralized and abstracted data graph walker to collect some info on the data graph for APC

Reviewed By: @jdelong

Differential Revision: D1098889
2013-12-30 12:04:56 -08:00
Simon Welsh aba50a36f4 Add Array to string conversion notice
Add Array to string conversion notice (and RaiseNotice IR
instruction needed to do so when using the JIT)

Closes #1314

Reviewed By: @alexmalyshev

Differential Revision: D1080985

Pulled By: @scannell
2013-12-30 12:04:52 -08:00
Brandon Wamboldt d26429c53d Fix preg_match_all requiring three parameters
preg_match_all's third parameter ($matches) should be an optional parameter.

Closes #1451

Reviewed By: @alexmalyshev

Differential Revision: D1112209

Pulled By: @scannell
2013-12-30 12:04:49 -08:00
javer 17fb5c2cce str_replace with empty array should return array
Handle empty array in str_replace like Zend and return an empty
array instead of null.

Closes #1452

Reviewed By: @alexmalyshev

Differential Revision: D1112243

Pulled By: @scannell
2013-12-30 12:04:45 -08:00
Sara Golemon 641b6bc9e0 Fix generation of parsers/scanners 2013-12-28 17:45:02 -08:00
Alex Malyshev 06f4711821 Fix callable typehint
The lexer and parser didn't know anything about the callable keyword,
and it was causing typehint errors when callable was being used inside a
namespace N, and the resulting typehint turned into "N\callable". Add
T_CALLABLE token to match zend, and fix TypeConstraint to respect it.

Reviewed By: @elgenie

Differential Revision: D1112493
2013-12-28 17:43:13 -08:00
Alex Malyshev ae9c577e7f Actually implement imagefilter()
imagefilter was using a function table filled with functions that just
threw NotSupportedException. Fixed them.

Reviewed By: @elgenie

Differential Revision: D1111814
2013-12-28 17:35:12 -08:00
Edwin Smith 4508e223f0 Visit all blocks when splitting critical edges.
Before we only were looking at blocks on the main trace.  This diff
removes the trace dependency, but still adds the middle-blocks to the
trace that owns the from-block.

Reviewed By: @ottoni

Differential Revision: D1111948
2013-12-28 17:35:08 -08:00
Edwin Smith f4d4b5110c Ignore traces in optimizeCondTraceExit
Same pattern as optimizeSideExitCheck.

Reviewed By: @ottoni

Differential Revision: D1111457
2013-12-28 17:35:05 -08:00
Jordan DeLong aab12b76e2 Filter systemlib-like units out of hhbbc for now
Reviewed By: @elgenie

Differential Revision: D1111801
2013-12-28 17:35:02 -08:00
Edwin Smith 21b7fcd24a Ignore traces in optimizeSideExitCheck()
Refactor optimizeSideExitCheck() into the postorder walk.  We were
visiting every instruction before, we really only need to visit
the last instruction of each block, and we can do it in the same
walk as the other jump optimizations.

Reviewed By: @ottoni

Differential Revision: D1111447
2013-12-28 17:34:58 -08:00
Edwin Smith 8036bfa80f Ignore traces in optimizeSideExitJccs()
Refactor optimizeSideExitJcc into the postorderWalk traversal.
We don't need to look at traces at all for this to work.

Reviewed By: @jdelong

Differential Revision: D1111176
2013-12-28 17:34:55 -08:00
Edwin Smith d819232fbb Ignore traces in eliminateUnconditionalJump()
This lays the groundwork for general jump optimizations and removes
the IRTrace dependency from eliminateUnconditionalJump().  Now we
traverse all blocks in postorder; two blocks joined by a trivial Jmp
can coalesced together.

Reviewed By: @ottoni

Differential Revision: D1111166
2013-12-28 17:34:52 -08:00
Alex Malyshev dc46425005 Don't expose doc comments of builtins through Reflection
Zend doesn't have doc comments for its builtins, so
Reflection{Method,Function,Class,Property}::getDocComment() will just
return false, but we have doc comments in systemlib/php and we return
those. Turns out this breaks Symfony, as they parse their own code and
then try to match their doc comments with those of Reflection, but throw
an exception when they fly up the interfaces on one of their classes and
hit ArrayAccess, which they never parsed doc comments for.

Reviewed By: @ptarjan

Differential Revision: D1106653
2013-12-27 21:58:45 -08:00
Eugene Letuchy bfa0c01f69 move trait alias modifier validation to parser ...
* remove a few places where we were attempting to do a modifier check
   at trait flattening time (badly?) and at class* time (waaay too late)
 * fix the glaring hole where 'visibility' modifier was interpreted as
   'not `static`' as opposed to ##public|private|protected|final## due to the way
   hphp.y happened to reuse modifiers

Reviewed By: @ottoni

Differential Revision: D1111920
2013-12-27 21:58:42 -08:00
Abel Nieto 25ad388943 Move FrozenSet to the HH namespace.
As per the title.

Reviewed By: @elgenie

Differential Revision: D1105025
2013-12-27 21:58:38 -08:00
Patryk Pomykalski 0f3e58f8ff Fix OOM while compiling mongo extension
gcc using all memory when compiling mongo/cursor.cpp

Closes #1414
Closes #1427

Reviewed By: @elgenie

Differential Revision: D1110301

Pulled By: @scannell
2013-12-27 21:58:35 -08:00
Sean Cannella a0a2fce43a Fix INI file typo
Fix INI file typo

Closes #1450

Reviewed By: @alexmalyshev

Differential Revision: D1112190
2013-12-27 21:58:31 -08:00
Brandon Wamboldt d0b98ce43d Fix preg_match returning false instead of null
preg_match/preg_match_all should return NULL not FALSE when invalid flags are passed.

Closes #1442

Reviewed By: @alexmalyshev

Differential Revision: D1111983

Pulled By: @scannell
2013-12-27 21:58:27 -08:00
Herman Venter 279a61338c Fix bugs in serialization of HHVM parse trees as PHP Code Model.
Remove left parentheses that survived edits and evolution. Fix the serialization of a simple function call to use the original function name. Make printExpressionVector treat a null list as an empty list. Use the original (scanned) string value when serializing scalar values. Make StaticClassName::outputCodeModel produce properly serialized strings (i.e. with headers). Use printStatementVector instead of just serializing each element of the vector in sequence. Adjust property counts to take into account null values. Tweak serialization of if statements to better deal with empty true blocks.

Reviewed By: duv

Differential Revision: D1097296
2013-12-27 21:58:23 -08:00
Paul Tarjan 77c6b843e1 actually send the response code
Closes #1416

Reviewed By: @sgolemon

Differential Revision: D1111910
2013-12-27 21:58:19 -08:00
Andre Costa b5d79c182e Fix redis' zRange and zRevRange
The commands zRange and zRevRange on redis weren't working. Since its
arguments are being passed to the command as an array, we must call
`processArrayCommand()` instead of `processCommand()`.

Reviewed By: @ptarjan

Differential Revision: D1111425
2013-12-27 21:58:16 -08:00
Edwin Smith 31e44e76af Move next edge from Block to IRInstruction
It's more precise to put the next edge on IRInstrution than on Block.
The current setup made it easier to add edges into the IR in general,
but this finally puts them where they should go.  This diff also
cleans a few things up: Edge now has an instruction field, which
avoids the need to set Edge.m_from whenever an instruction's block
changes; Edges are allocated separately, and only for instructions
that need them, which reduces sizeof IRInstruction by 16 bytes.
Every block must now end with a control flow instruction, even if it's
just a jmp to a next block.  Unnecessary jumps should already be
removed at code-gen time.

This diff also adds a Branch flag.  Any instruction that could have
an edge must have either the Branch flag or MayRaiseError flag, in
which case m_edges is never null (but Edge::to could be null).
Other instructions must have m_edges == null.  Because of this, it
was necessary to factor the compare instructions into the ones that
throw, with MayRaiseError set plus a catch edge, and ones that don't,
with no edges.

Reviewed By: @jdelong

Differential Revision: D1109820
2013-12-27 21:57:55 -08:00
Guilherme Ottoni a212a099b4 Only consider classes that are final for specialization
That's a requirement from how we generate specialized guards, so don't
even let non-final classes enter into the type system.

Reviewed By: aravind

Differential Revision: D1109309
2013-12-27 21:52:39 -08:00
Guilherme Ottoni d2651ac64b Only generate profiling translations after JitProfileRequests for functions that are already being profiled
Otherwise, for functions that we never saw during the first
Eval.JitProfileRequest requests, we'll generate profiling translations
that never get retranslated.

Reviewed By: aravind

Differential Revision: D1104276
2013-12-27 21:52:36 -08:00
Sara Golemon 33a1bfa3ed Refactor ext icu a bit
* Reduce copypasta by inheriting from a common IntlRequestData
  * Move some stuff into headers for interop between intl components

Reviewed By: @ptarjan

Differential Revision: D1107269
2013-12-27 03:58:24 -08:00
Paul Tarjan 705fa52c49 use writeBE instead of append for fastcgi
Reviewed By: @simpkins

Differential Revision: D1111292
2013-12-27 03:57:16 -08:00
Eugene Letuchy 76991160ef trait requires: check trait constraints on recursive traits [4/4]
traits should be able to state what they require of their
 subclasses:

  require implements SomeInterface
  require extends SuperClass

 This will aid hack in being able to typecheck trait bodies as
 well as allowing more disciplined trait coding (tying traits to
 class hierarchies, as happens in practice).

 This diff checks implements and extends requirements on recusively
 used traits (class uses trait that itself uses another trait that has
 requirements). The approach chosen is to walk the trait hierarchy for
 each Class instantiation; an alternative approach would be to keep a
 list of requirements in each trait Class and add to it.

 Note that nothing is done in repo mode, since traits end up flattened
 into using classes.

Reviewed By: @jdelong

Differential Revision: D1101640
2013-12-27 03:57:12 -08:00
Eugene Letuchy 3f608b310e trait requires: check traits constraints at use time [3/4]
traits should be able to state what they require of their
 subclasses:

  require implements SomeInterface
  require extends SuperClass

 This will aid hack in being able to typecheck trait bodies as well as
 allowing more disciplined trait coding (tying traits to class
 hierarchies, as happens in practice).

 This diff introduces the checking of implements and extends
 constraints on the using class, and (less importantly) enforces that
 we're dealing with the right kind of class on traits.

Reviewed By: @jdelong

Differential Revision: D1101637
2013-12-27 03:57:09 -08:00
Eugene Letuchy affb8f79da trait requires: thread into preclass [2/4]
traits should be able to state what they require of their
 subclasses:

  require implements SomeInterface
  require extends SuperClass

 This will aid hack in being able to typecheck trait bodies as well as
 allowing more disciplined trait coding (tying traits to class
 hierarchies, as happens in practice).

 This diff moves the trait requirement declarations into the preClass,
 but doesn't yet check them

Reviewed By: @jdelong

Differential Revision: D1101621
2013-12-27 03:57:05 -08:00
Jordan DeLong 926cac6f07 Default StatCache to off
We're turning it off in all of our configs, but we left it on
in the example OSS configs.  There's some sort of race-issue reported
on github, so let's turn the default to the tested configuration.

Closes #1402 (not the underlying problem, but we're not really
planning to make StatCache better any time soon).

Reviewed By: @edwinsmith

Differential Revision: D1108713
2013-12-27 03:57:02 -08:00
Guilherme Ottoni f5acb51e97 Teach prediction optimization about no-dest IncRefs
The type prediction optimization checks for a specific pattern, which
changed once we dropped the dest operand of IncRefs.  This diff fixes
it.

Reviewed By: @jdelong

Differential Revision: D1110700
2013-12-27 03:56:58 -08:00
Jordan DeLong b1d75c750e Fix bugs relating to Uninits in the control-flow local type updates
locAsCell behaves like CGetL: it returns a subtype of
TInitCell (uninits become init nulls, and it dereferences TRef).
Since in these grouping functions we're about to set the loc back
"unchanged", we want something that does the deref but not the
conversion of uninit to init.

Reviewed By: @edwinsmith

Differential Revision: D1109766
2013-12-27 03:56:55 -08:00
Jordan DeLong 68b8e71a15 Hook Op::JmpNS up to pass through in HHBBC
For now did it the easy way.

Reviewed By: @edwinsmith

Differential Revision: D1103613
2013-12-27 03:56:52 -08:00
Jordan DeLong 1e0b802984 Replace NoSurprise metadata with a JmpNS instruction
Just is easier to manipulate bytecode than metadata.  This
doesn't hook it up in hhbbc yet.  Also I removed surprise flag checks
from IterBreak: they aren't ever going to jump to loop heads.

Reviewed By: @markw65

Differential Revision: D1103402
2013-12-27 03:56:48 -08:00
Alex Malyshev 3ba683b441 Replace macros in Simplifier with templates
Replaces SIMPLIFY_{CONST,COMMUTATIVE,DISTRIBUTIVE} with templated
functions instead.

Reviewed By: @jdelong

Differential Revision: D1104151
2013-12-27 03:56:41 -08:00
Sara Golemon 7f2b1ced80 Remove the need to export HPHP_HOME when building
"Detect" HPHP_HOME as the location of the main CMakeLists.txt
file and plumb it through to child scripts from there.
2013-12-27 03:10:16 -08:00
Sara Golemon 209927b104 Some spring cleaning for the cmake file
Don't even check USE_HHVM/USE_HPHPC, hphpc died months ago.
HHVM_BINARY and HHVM_LIB_PATH_DEFAULT defines are no longer used.
HHVM_PATH is specific to test.
2013-12-27 03:10:16 -08:00
Sara Golemon d74565b37e Rename CMake LibUODBC module.
Oops.  I misnamed it.
2013-12-27 03:10:15 -08:00
Sara Golemon ff58f003aa Be honest, we're just not going to support 32bit.
The JIT specifically emits 64-bit x86 and will do so for
the forseeable future.
2013-12-27 03:10:15 -08:00
Sara Golemon 579fb44d4b Strip generator's path info out of generated ini-parser file 2013-12-27 03:10:15 -08:00
Guilherme Ottoni 0799ab3745 Change eliminateRefcounts to convert instructions to Nops instead of erasing them
Otherwise the block may become empty and validation passes start to
complain.  It's simpler to just convert the instructions to Nop and
let DCE take care of cleaning things up.

Reviewed By: aravind

Differential Revision: D1109291
2013-12-26 11:02:01 -08:00
Sean Cannella be7fb2055d Fix ASAN tests
Fix use-after-free with imported systemlib module names

Reviewed By: @jdelong

Differential Revision: D1111011
2013-12-26 11:01:58 -08:00
Jordan DeLong 622b5c09a4 Update NEWS for Appleseed
Reviewed By: @scannell

Differential Revision: D1110400
2013-12-26 11:01:55 -08:00
reeze 4e697550da Fix ReflectionClass::implementsInterface with \
Fixed ReflectionClass::implementsInterface() with black slash
prefixed interface name

Closes #1424
Closes #1430

Reviewed By: @ptarjan

Differential Revision: D1110811

Pulled By: @scannell
2013-12-26 11:01:51 -08:00
Brandon Wamboldt fa60b79bd3 Fix SplDoublyLinkedList when using array syntax
If you append items to a SplDoublyLinkedList using array syntax
($foo[] = 'bar'), the tail would not be updated.

Example:

<?php
$stack = new SplStack();

$stack[] = "var1";
$stack[] = "var2";
$stack[] = "var3";

foreach ($stack as $var) {
    echo $var . "\n";
}

HHVM Output:

    var1

Correct Output:

    var3
    var2
    var1

Closes #1415
Closes #1421

Reviewed By: @alexmalyshev

Differential Revision: D1110142

Pulled By: @scannell
2013-12-26 11:01:48 -08:00
Sam Boyer 447f17f1e2 SplObjectStorage mutation fix
The current reimplementation of SplObjectStorage does not allow mutation
of "info" values attached to object keys in the case where the object is
already present in the object. This is inconsistent with PHP's behavior.

Closes #1388

Reviewed By: @ptarjan

Differential Revision: D1108349

Pulled By: @scannell
2013-12-26 11:01:44 -08:00
Patryk Pomykalski 7a7b09894a Fixed setIteratorMode() in SplStack and SplQueue
setIteratorMode in SplStack didn't throw exception when mode
was invalid.

Closes #1426

Reviewed By: @alexmalyshev

Differential Revision: D1110182

Pulled By: @scannell
2013-12-26 11:01:41 -08:00
Brandon DuRette 365c56fdc4 Make strrchr more compatible with Zend
The contract for strrchr is "If needle contains more than one character,
only the first is used". The implementation was using strrpos which
scans for the entire string, not just the first character, resulting in
an incompatibility. This PR request resolves that incompatibility.

Also, for the purposes of strrchr, zend treats the empty string as a NUL
character. This happens because the empty string is (apparently) handled
by the second rule for needle: "If needle is not a string, it is
converted to an integer and applied as the ordinal value of a
character."

Closes #1394

Reviewed By: @JoelMarcey

Differential Revision: D1108545

Pulled By: @scannell
2013-12-26 11:01:38 -08:00
Simon Welsh a24d2c619a Add ZendParamModeFalse
Add ZendParamModeFalse for chdir-like functions

Reviewed By: @ptarjan

Differential Revision: D1108735

Pulled By: @scannell
2013-12-26 11:01:34 -08:00
Sean Cannella 9b1c9e5e08 Change error exit code to be consistent with Zend
Errors now return -1 like PHP does.

Closes #1350
Closes #1405

Reviewed By: @ptarjan

Differential Revision: D1108693
2013-12-26 11:01:31 -08:00
Simon Welsh 4f5a3795b8 Pass along error number when handling a fatal error
As no error number was being passed when a fatal error occurred, error_get_last() in a shutdown handler wasn't able to check if the error was fatal.

Closes #1408

Reviewed By: @alexmalyshev

Differential Revision: D1110032

Pulled By: @scannell
2013-12-26 11:01:27 -08:00
Brandon DuRette 90e2969feb Zend compatibility - stripslashes
Zend's implementation of stripslashes removes a trailing
backslash in a string, except in the empty string it is replaced by a
NUL. Prior to this PR, HHVM's implementation always replaced the
trailing backslash with a NUL. The reason is, HHVM unconditionally
appended the character following a backslash. When the string ends in
backslash, the following character is the null-terminator of the
underlying C-string.

This was identified because of a failing test in the WordPress test
suite.

Closes #1423

Reviewed By: @alexmalyshev

Differential Revision: D1110135

Pulled By: @scannell
2013-12-26 11:01:24 -08:00
Simon Welsh 08395de8ca fix ob_get_contents return value
ob_get_contents returns false if not currently buffering output

Closes #1429

Reviewed By: @alexmalyshev

Differential Revision: D1110757

Pulled By: @scannell
2013-12-26 11:01:20 -08:00
Sean Cannella deb0b232e2 Fix test runner
Fix test runner

Reviewed By: @edwinsmith

Differential Revision: D1110872
2013-12-24 14:11:04 -08:00
Benjamin Zikarsky d469cde767 Reestablished PHP 5.3 compatibility in test runner
Fix compat issues with Zend PHP 5.3

Closes #1420

Reviewed By: @ptarjan

Differential Revision: D1110759

Pulled By: @scannell
2013-12-24 14:11:03 -08:00
Sumeet Ungratwar 23efdd51d7 Made paramater of newInstanceArgs method optional
PHP documentation requires it to be optional, passing no
argument would call the constructor taking no arguments.

Reviewed By: @ptarjan

Differential Revision: D1109795
2013-12-24 14:11:03 -08:00
Paul Tarjan a19766f3de fix DOCUMENT_ROOT for fastcgi
We shouldn't have spcialized code in here for fastcgi, and it didn't even work.

Reviewed By: @markw65

Differential Revision: D1109072
2013-12-24 14:11:03 -08:00
Paul Tarjan dd1259afba Allow fastcgi to use the DOCUMENT_ROOT from the web server
We shouldn't use the current directory or the configured `SourceRoot` since the webserver could have many virtual hosts and always will send us a DOCUMENT_ROOT header.

The only scary part of the change is checking for `sourceRoot` instead of `getDocumentRoot` but I think it is right.

Reviewed By: @markw65

Differential Revision: D1108017
2013-12-24 14:11:02 -08:00
Jordan DeLong 5d674bb81b Fix an issue with empty async function closures---finishStatement off by one
Also remove a "useless non-terminal" warning (an old rule was
accidentally left in).  This only affected empty async function
closures, since the onClosure itself wasn't off by one, and all
finishStatement does is replace empty statement lists.

Reviewed By: @edwinsmith

Differential Revision: D1109810
2013-12-24 14:11:02 -08:00
Edwin Smith c0995e0acd Fix names of a bunch of opcodes in ir.specification
It looks like someone renamed them in the source code but
forgot to update the spec.

Reviewed By: @jdelong

Differential Revision: D1109814
2013-12-24 14:11:01 -08:00
Sumeet Ungratwar e68e5f08f5 fix ini_get('memory_limit')
No information of input string was stored by ini_set. For e.g.
10K was converted to 10240 which ini_get('memory_limit') returned.
Solution was to store user passed in string and convert it to integer
whenever required

Reviewed By: @ptarjan

Differential Revision: D1109228
2013-12-24 14:11:01 -08:00
mwilliams 8107a50d5f Better type inference for collections
Let type inference know the actual type for T_COLLECTION
expressions. Also mark them "definitely not null".

Reviewed By: @jdelong

Differential Revision: D1109650
2013-12-24 14:11:01 -08:00
Jordan DeLong 0683d2006d Remove various subop static_casts in abstract-interp.cpp
These are no longer needed now that the opcode table knows
about subop types.

Reviewed By: @swtaarrs

Differential Revision: D1102943
2013-12-24 14:11:00 -08:00
Jordan DeLong c02cbd6273 Update local types for the bytecode sequences CGetL; InstanceOfD; Jmp{N,}Z
Reviewed By: @dariorussi

Differential Revision: D1101639
2013-12-24 14:11:00 -08:00
Jordan DeLong 25a3e28b41 Remove simplifySpillStack's attempted dead store elimination
It isn't aware of situations where autoload can clobber stack
slots.

Reviewed By: @ottoni

Differential Revision: D1107251
2013-12-24 14:10:59 -08:00
Jordan DeLong 456d625c0e Fix a bug in FPI region recording for internal async function calls
The FPIRegionRecorder is notoriously easy to misuse.

Reviewed By: @dariorussi

Differential Revision: D1107441
2013-12-24 14:10:59 -08:00
Drew Paroski 254e68c0b0 Lambda syntax
Reviewed By: @jdelong

Differential Revision: D1108850
2013-12-24 14:10:58 -08:00
Eugene Letuchy c82e54b087 trait requires: add basic syntax [1/4]
traits should be able to state what they require of their
 subclasses:

  require implements SomeInterface
  require extends SuperClass

 This will aid hack in being able to typecheck trait bodies as well as
 allowing more disciplined trait coding (tying traits to class
 hierarchies, as happens in practice).

Reviewed By: @jdelong

Differential Revision: D1101619
2013-12-24 14:10:58 -08:00
mwilliams c5746986df Analyze systemlib.php in repo mode
This lets us analyze systemlib.php in wholeprogram mode. It also
analyzes the various extension php files in wholeprogram mode. Previously,
whole program mode was almost entierly unaware of the mini-systemlibs, and
things only really worked by luck, and bugs in the way they were processed.

Reviewed By: @jdelong

Differential Revision: D1099615
2013-12-24 14:10:58 -08:00
Benjamin Zikarsky 22b4777d5c Included ReactPHP and Ratchet to framework runner
Included ReactPHP and Ratchet to framework runner

Closes #1404

Reviewed By: @ptarjan

Differential Revision: D1108669

Pulled By: @scannell
2013-12-24 14:10:57 -08:00
Benjamin Zikarsky 328ca374c7 Add monolog to framework test runner
Adds monolog to framework test runner

Closes #1397

Reviewed By: @ptarjan

Differential Revision: D1108661

Pulled By: @scannell
2013-12-24 14:10:57 -08:00
Paul Tarjan be5279d633 refactor Closure getting ready for bindTo
Reviewed By: @jdelong

Differential Revision: D1106189
2013-12-24 14:10:56 -08:00
Paul Tarjan 812727c240 maybe fix iopCreateCl race
@markw65 purported that maybe this was the cause of the race. I agree it is worth trying

Reviewed By: @markw65

Differential Revision: D1106725
2013-12-24 14:10:56 -08:00
Sean Cannella d93cdc2ca8 Support oniguruma-5.9.4+
Newer versions of oniguruma have a type collision without this define, see https://github.com/javer/gentoo-overlay/pull/3#issuecomment-30758478.

Closes #1400

Reviewed By: @ptarjan

Differential Revision: D1108355
2013-12-24 14:10:56 -08:00
Simon Welsh eebe258165 Add SilverStripe to the test runner
Add SilverStripe to the test runner

Closes #1390

Reviewed By: @ptarjan

Differential Revision: D1107161

Pulled By: @scannell
2013-12-24 14:10:55 -08:00
Abel Nieto ba00db7b3d Migrate FrozenVector to the HH namespace.
As per the title.

Reviewed By: @paroski

Differential Revision: D1091837
2013-12-24 14:10:55 -08:00
Paul Tarjan 39b21a2fd7 filter_var snapshot (take 2)
Unrevert the filter_var diff. Also fix a bug where it isn't snapshotted in the request path.

Reviewed By: @JoelMarcey

Differential Revision: D1104270
2013-12-24 14:10:54 -08:00
Joel Marcey 4b9aec1592 Better match Zend finfo
NULL is allowed for some string parameters in some functions of finfo. In fact, NULL is the default value. e.g., http://php.net/manual/en/function.finfo-open.php

Our current implementation did not allow nullable strings. We would get errors like:

HipHop Fatal error: Argument 1 passed to foo() must be an instance of string, null given in /tmp/strtest.php on line 4

Make these string nullable (e.g. ?string)

phpbb was running into this issue using finfo

Reviewed By: @ptarjan

Differential Revision: D1107796
2013-12-24 14:10:54 -08:00
Abel Nieto 021d6eec40 Migrate Set to the HH namespace.
Move the Set collection class to the HH namespace.

So now get_class(new Set()) === "HH\Set".

The auto-import mechanism in place makes the change transparent most of the
time (e.g. developers can simply use "Set" in their code), but the namespace
shows up in some cases, serialization being a notable one.

Depends on D979471.

Reviewed By: @elgenie

Differential Revision: D1081929
2013-12-24 14:10:54 -08:00
Abhinav Batra 8765e705bf Resource To Array Conversion
Converted resource to an array contatining the resource

Reviewed By: @ptarjan

Differential Revision: D1107620
2013-12-24 14:10:53 -08:00
Brandon DuRette 65bdcabe8e str_replace counts fail to accumulate with arrays
The $count parameter of str_replace is supposed to return the total
number of string replacements performed. This was only working correctly
when both $search and $subject were strings. When either or both are
arrays, the counts need to accumulate across all replacements. The code,
as written, was only returning the replacement count for the last pair
of values.

Closes #1383

Reviewed By: @ptarjan

Differential Revision: D1106935

Pulled By: @scannell
2013-12-24 14:10:53 -08:00
Dario Russi 6c277e96c7 fix leak in iter_next_apc for string keys
We were inc-ref'ing keys one too many

Reviewed By: @jdelong

Differential Revision: D1108033
2013-12-24 14:10:52 -08:00
bsimmers 3a9e0f5e44 Fix LdThis in unbound closure bodies
Loading $this will always fail in these, but we shouldn't dump core
while processing the unreachable code.

Reviewed By: @ottoni

Differential Revision: D1107377
2013-12-24 14:10:52 -08:00
Sara Golemon dcc7e3d788 Make unix_odbc support optional 2013-12-24 14:10:52 -08:00
Pedro Eugenio Rocha Pedreira 8a0e601bf4 hhvm: initial implementation of the php_odbc API
Reviewed By: @ptarjan

Differential Revision: D1058022
2013-12-24 14:10:36 -08:00
Guilherme Ottoni 711851fc71 Trigger Optimize retranslations at all function entries
This diff changes things so that Profile translations for all function
entries (normal entry plus DV funclets) trigger Optimize
retranslations in PGO mode.  This fixes the PGO mechanism for
irregular functions (e.g. array_map) that don't follow the defunct
bytecode rule that DV funclets fall-through one into another and then
into the function's main entry (function base).

Also did a few cleanups along the way.

Reviewed By: @bertmaher

Differential Revision: D1108164
2013-12-24 09:59:19 -08:00
mwilliams 272874f432 Fix crash when a custom init function throws
Classes derived from exception have a custom-instance-init
method which gets called before the constructor. It can throw (eg
if a timeout occurs), so allocObj needs a catch trace, and allocObjFast
shouldn't be called on classes derived from Exception.

Reviewed By: @edwinsmith

Differential Revision: D1107437
2013-12-24 09:59:15 -08:00
Edwin Smith a4c6946652 Allocate intervals individually
Looking at XLS trace dumps, most units have a lot less
intervals than SSATmp ids.  Allocating them separately
should save a bunch of memory, but also avoid any hazards
from std::vector moving them during register allocation.
(which happened to me once, w/out a reserve call).

Reviewed By: @jdelong

Differential Revision: D1107035
2013-12-24 09:59:12 -08:00
Bert Maher d93cf9b2ac Use base 10 for bytecode offsets in CFG printer
Since TRACE=printir uses base 10, I prefer using it here too.
But feel free to veto.

Reviewed By: @ottoni

Differential Revision: D1106785
2013-12-24 09:59:08 -08:00
Chip Turner ded68bbfe7 Properly split host:/path/to/socket strings
We weren't properly splitting the mysql socket form of connect
strings when ipv6 support was added.  The net result was a string of the
form:

localhost:/path/to/socket

was trying to open the socket 'path/to/socket' rather than
'/path/to/socket'

Reviewed By: @ptarjan

Differential Revision: D1107623
2013-12-24 09:59:04 -08:00
bsimmers 1e2a272df5 Add catch trace to RaiseWarning in emitDiv
Anything that can throw must have a catch trace.

Reviewed By: @bertmaher

Differential Revision: D1106629
2013-12-24 09:58:59 -08:00
bsimmers 2973400e8e Loosen assert in emitVerifyParamType
This should unbreak the legacy region selector in opt builds while I
try to figure out why it's firing.

Reviewed By: @edwinsmith

Differential Revision: D1105296
2013-12-24 09:58:55 -08:00
bsimmers 873354334b Misc tweaks/fixes
- aprof needs 6 digits just like a
- return the proper sizes for the admin port check-health command
- make an assert in emitVerifyParamType more useful

Reviewed By: @bertmaher

Differential Revision: D1103500
2013-12-24 09:58:51 -08:00
Herman Venter eb582bd73f Add parser support for language integrated query expressions.
This diff adds syntax to hphp.y, context sensitive keywords to hphp.ll, AST classes, a dummy emitter that just turns a query expression into a serialized CodeModel, as well as several test cases that exercise all options in the syntax and tests that the new keywords can still be used outside of queries.

The PHP syntax is exactly the same as the C# syntax.

There is significant restriction not present in C#, but necessary to get rid of shift reduce conflicts in Bison, namely: a query expression can only appear on the right hand side of an assignment to simple variable and as the expression of a return statement.

The need for making the "from" keyword context sensitive also precludes changing the syntax of "from $row in $table" to a more PHP compatible "from $table as $row", since $row can be any kind of expressions and hence does not provide enough context for the scanner to determine that the from token starts a query.

A query expression compiles to a call looking a bit like
   $rc = $c->executeQuery("serialized ast for normalized query expression", argvector);
   foreach ($rc as $re) { yield some_expression_containing($re); }
The $c is the value of the expression in the first from clause. The serialized ast represent the query expression after all parts of it that can be executed locally have been removed. Argvector is a vector of values that were computed locally. $rc is collection of tuples received from the query engine. The "foreach" turns the tuples into values as specified by the select clause.

This diff does not complete the implementation of code generation for query expressions. Specifically, the ast is not normalized, the argvector is null and the foreach is missing. I would like to get this diff out as is now in order to enable people to write query providers and test them with actual query expressions.

Reviewed By: @paroski

Differential Revision: D1088496
2013-12-24 09:58:51 -08:00
Paul Tarjan 745a3d8e41 fix preg segfault
`php_pcre_replace` isn't guaranteed to return a String or Boolean. Lets just proxy the result back if it isn't a string instead of assuming and segfaulting the async tier.

Reviewed By: @markw65

Differential Revision: D1106633
2013-12-24 09:58:37 -08:00
Edwin Smith 6eb84e4faf Convert XLS m_pending to priority_queue
Simpler than explicitly doing heap operations on a vector.

Reviewed By: @swtaarrs

Differential Revision: D1106561
2013-12-24 09:58:33 -08:00
Sean Cannella 1b389496b4 Merge pull request #1422 from brandonwamboldt/fix-markdown-1
Fix some minor markdown formatting issues
2013-12-23 11:25:44 -08:00
Brandon Wamboldt fb25361d62 Fix some minor markdown formatting issues 2013-12-22 10:16:38 -08:00
Sean Cannella 4df62bd80a Merge pull request #1407 from brandonwamboldt/fix-cmake-priority
Check for 32 bit OS first in the CMake file
2013-12-20 15:16:59 -08:00
Brandon Wamboldt cbd9f4ee37 Check for 32 bit OS first in the CMake file
Otherwise users may waste time installing missing dependencies just to get that error at the end
2013-12-20 15:11:41 -08:00
Sean Cannella ea44e6760d Merge pull request #1403 from javer/cmake-freetype
Fix cmake freetype include directory
2013-12-20 12:34:12 -08:00
javer c3bd6fa66a Fix cmake freetype include directory
Fixed overwriting FREETYPE_INCLUDE_DIRS when freetype located at
non-default path.
2013-12-20 19:32:58 +02:00
Sara Golemon 8525d97318 Add hash_copy()
Missing piece of hash API

Reviewed By: @ptarjan

Differential Revision: D1104737
2013-12-19 12:11:42 -08:00
Bert Maher c407042c11 Remove useHHIR param from TraceletContext::recordRead
It doesn't look like this flag actually has any effects
now... am I missing something?

Reviewed By: @swtaarrs

Differential Revision: D1106158
2013-12-19 12:11:35 -08:00
Bert Maher 686f440b8a More vestigial bits of Mem and Refs flags
Missed these pieces when killing them

Reviewed By: @jdelong

Differential Revision: D1106119
2013-12-19 12:11:28 -08:00
Edwin Smith c962d98717 Remove dead dtorStubs
They were dead code.  After a brief chat on IRC we agreed
to get rid of them.

Reviewed By: @jdelong

Differential Revision: D1104938
2013-12-19 12:11:21 -08:00
Paul Tarjan 9d80cda2cd throw an exception if the DateTime is invalid (take 2)
This reverts commit 14ce743eb5b6f82a411aff93d4129344e3ea02a3.

Reviewed By: @elgenie

Differential Revision: D1073188
2013-12-19 12:11:17 -08:00
Paul Tarjan 50aff1943e Fix Phar's directory detection
I screwed up the prefix check. Something that is a directory has to have a `/` between the prefix and the file, not just any character.

Closes #1334

Reviewed By: @JoelMarcey

Differential Revision: D1104260
2013-12-19 12:10:41 -08:00
Bert Maher 83564f81b1 Remove Mem and Refs flags, because they are dead
These flags aren't used for anything, so it's hard to know
what semantics they're supposed to have.  If we want to add something
similar in the future it will probably be just as easy to reason
through what we want from each opcode instead of trying to use these.

Reviewed By: @jdelong

Differential Revision: D1100600
2013-12-19 12:10:37 -08:00
Owen Yamauchi d8bd94843c ARM codegen for LdStack and DbgAssertRefCount
This was the top punt. Implementing that just moved a bunch of punting
to DbgAssertRefCount, so I implemented that too.

Reviewed By: @edwinsmith

Differential Revision: D1104532
2013-12-19 12:10:33 -08:00
Mike Magruder 45e315e85b Experimental memoization profiler
A small profiler which looks for memoization opprotunities. It's fairly ghetto right now, and dumps its output to stderr, but it's useful as is now so I'm gonna put it in. It's not hooked up anywhere, but if you're interested in how to hook it up, run it, and intrepret the output lemme know.

Reviewed By: @hermanventer

Differential Revision: D1100611
2013-12-19 12:10:29 -08:00
Owen Yamauchi 56509ff711 Put abi-x64.h in X64 namespace
For consistency with abi-arm.h. This doesn't cause too much X64::
line-noise (since files like code-gen-x64.cpp just do `using namespace
X64`), and it shines a light on some spurious platform dependencies,
which are now well-marked for when future ARM codegen stumbles across
them.

Reviewed By: @edwinsmith

Differential Revision: D1104447
2013-12-19 12:10:25 -08:00
Sara Golemon d8496058f7 Merge pull request #1381 from PocketRent/find-libs
Improve detection on FindLibs
2013-12-19 10:38:58 -08:00
James Miller 684fe9dcf8 Improve detection on FindLibs 2013-12-19 11:39:40 +13:00
Alex Malyshev b3640c2a87 Only save SessionRequestData's default module once
It was getting overrwritten every time session_set_save_handler() was
being called.

Also ext_session_request_shutdown() was calling close() on the session
module twice, fix that.

Reviewed By: @ptarjan

Differential Revision: D1101153
2013-12-18 11:42:08 -08:00
Daniel Sloof e5f1b28a8b Close pdo connection after request ends
When a request finishes and the PDO connection is not closed in
userland, we need to explictly close it to prevent excessive amount of
connections (and eventually causing MySQL to reject them).

This can obviously be solved in userland by closing the connection in a
register_shutdown_function, but we need to be consistent with PHP.

Closes #1345

Reviewed By: @markw65

Differential Revision: D1098327

Pulled By: @scannell
2013-12-18 11:42:05 -08:00
Edwin Smith a06ee23b39 Rename EvalHHIRAllocXMMRegs to EvalHHIRAllocSIMDRegs
Now the option name isn't arch-specific.

Reviewed By: @bertmaher

Differential Revision: D1104420
2013-12-18 11:42:01 -08:00
Patrick Dowell d1ff787b46 fix to allow proc_open() to accept php://stdin as stdin
I added some code to the openFile function in runtime/ext/ext_process.cpp that accounts for the case when the user calls proc_open() using
php://stdin as stdin for the process spawned.

Reviewed By: @ptarjan

Differential Revision: D1094713
2013-12-18 11:41:58 -08:00
Max Wang 1a1789fa85 Implement replace{C,TV} on VM stack
These are just wrappers for the behavior of pop{C,TV}() and pushFoo(),
but without the inc/dec.

Reviewed By: @jano

Differential Revision: D1100964
2013-12-18 11:41:54 -08:00
mwilliams ba14fac25d Include template functions in perf-pid.map
Template symbols are tagged WEAK, and neither
LOCAL nor GLOBAL. We need to include those in perf-pid.map
though.

Reviewed By: @ottoni

Differential Revision: D1103103
2013-12-18 11:41:51 -08:00
mwilliams 3da6f82fd4 Don't warn for system functions that aren't known at static analysis time
The c++ implementation of array_filter was recently removed,
and static analysis doesn't see .hhas files, so is now unaware of the
function, and so spits out UnknownFunction warnings. In addition, until
D1099615 lands, functions defined in mini-systemlibs aren't known either,
and so result in similar warnings.

This is a quick hack to eliminate those, so we can hotfix it to rc. I'll
do a better diff on master on top of D1099615.

Reviewed By: @ptarjan

Differential Revision: D1103230
2013-12-18 11:41:47 -08:00
Sean Cannella 8decf913ca Reduce hhprof crashes
- Memory profiling should not result in allocations and VM re-entry if we're crashing
- Fix call fixup in function prologue

Reviewed By: @jdelong

Differential Revision: D1102730
2013-12-18 11:41:43 -08:00
bsimmers ed492718fd Disable flaky zend test
Reviewed By: @jdelong

Differential Revision: D1103516
2013-12-18 11:41:36 -08:00
bsimmers 87c71e05a2 Revert "make filter_var snapshot the variables at request start"
This reverts commit de0579e00c94928357588ceb2796294be9110178. It broke
test/quick/debugger/flow.php

Reviewed By: @ptarjan
2013-12-18 11:41:32 -08:00
Jordan DeLong 686b040e70 Several type system bug fixes, and improve inference on jmpType for IsTypeL
Several of the functions relating to option types were wrong
if the option type had data (e.g. types like ?SStr="foo").  It's
easier to get everything right after adding TOptC{Str,Arr} types,
although I don't think they should happen much, so I added those.
Also, update IsTypeL; Jmp cases to do as good as the CGetL; Jmp cases
do with optional object subtypes.

Reviewed By: @edwinsmith

Differential Revision: D1099593
2013-12-18 11:41:29 -08:00
Jordan DeLong fe90718182 Fix some reflection under hhbbc, and for HNI functions after "refactor func.h"
The hhbbc case was a bug---for HNI it is a change in behavior
that looks unintentional, but I sorta doubt anything relies on the old
behavior.  Also remove the StringData* overload so you can't
accidentally call the wrong function, and add documentation.

Reviewed By: @alokmenghrajani

Differential Revision: D1099590
2013-12-18 11:41:25 -08:00
Jordan DeLong 80a34a78eb Update the types of locals when conditionally branching on their types
This makes some of the common patterns of user-level explicit
type tests update the types of locals on each side of the conditional
branch.

I thought a bit about how to do this without just pattern matching on
common bytecode pairs, but this seems the simplest way to get what we
want for now.  One other idea basically would involve a whole pass to
figure out which stack slots have the same types as which locals
(taking into account things that kill that relationship), which seemed
like it was unlikely to get any more types (although it would be "more
general").

Still a TODO is instanceof + jmp.

Reviewed By: @edwinsmith

Differential Revision: D1093057
2013-12-18 11:41:21 -08:00
Jordan DeLong 93733eed2d Fix a bug in preOptimizeStLoc
With the control-flow sensitive local type inference in
hhbbc, a local was being asserted as Type::Null.  Because
isKnownDataType returned true, preOptimizeStLoc decided that
converting that local from KindOfUninit (the actual live type) to
KindOfNull did not require storing a new m_type value, leading to a
crash down the line in the next translation.  I tried cleaning up
isKnownDataType but too many things depend on it (also it's a little
conceptually shaky because of how we deal with Str), so for now tasked
and just fixed this function.

Reviewed By: @swtaarrs

Differential Revision: D1099460
2013-12-18 11:41:17 -08:00
Guilherme Ottoni ca5dfe2457 Fix bugs in SetOpL
I ran into these while trying a perf diff that didn't turn out to help perf.

Reviewed By: @swtaarrs

Differential Revision: D1102269
2013-12-18 11:41:13 -08:00
Paul Tarjan 9ea6701165 make filter_var snapshot the variables at request start
I made an extensible way for extensions to run some code at the start of every request.

Reviewed By: @alexmalyshev

Differential Revision: D1101191
2013-12-18 11:41:10 -08:00
Paul Tarjan 8ab4b9f75b Revert "[ext_asio] Process ready wait handles in LIFO rather than FIFO order"
This reverts commit ff25227dea707166baf9fcb14a4940d503252e5f.

This has been reverted in 4 releases. That is just unacceptable. Please don't commit this until it can go out with a release.

Reviewed By: @jano

Differential Revision: D1102064
2013-12-18 11:41:06 -08:00
Jordan DeLong 1d936c49f5 Hackathon: initial version of php-to-hhas printer
Reviewed By: @edwinsmith

Differential Revision: D1099109
2013-12-18 11:41:02 -08:00
Jordan DeLong 67ab891ef6 Make OA arguments carry type information in the opcode table
Use this to unify all our to/from string functions for OA
arguments.  Also removes some of the remaining casting to/from
unsigned char.

Reviewed By: @swtaarrs

Differential Revision: D1098649
2013-12-17 13:59:07 -08:00
Jordan DeLong a5b1a0eb6b Turn IncDecOp/SetOpOP into enum classes and add hhas support for them
I'm planning to make the opcode table support strongly-typed
OA args, so I'll convert the remaining OA's to have enum classes.
After this diff, only BareThis uses an OA arg without an associated
enum class (I'll change that if making OA take a type argument turns
out to be good).

Reviewed By: @swtaarrs

Differential Revision: D1097329
2013-12-17 13:59:06 -08:00
Paul Tarjan 55289dc16f Make FastCGI less magical for headers
When I changed `getHeaders()` to be the same for fastcgi as all the other transports I didn't notice julk has put in special rules to deal with the fact they weren't the same. Rip that out.

This makes `$_SERVER` contain `HTTP_HOST` instead of just `HOST`.

Reviewed By: @sgolemon

Differential Revision: D1100779
2013-12-17 13:59:06 -08:00
Owen Yamauchi d2e18efee7 Get rid of x64-ARM register mapping
This gets ARM register allocation to use XLS properly.

- x2a is now just a type conversion function. This is the smoothest way
  of getting around the PhysReg::operator[] problem. I don't think this
  is the ideal way forward because it means the ARM backend is still a
  second-class citizen in a way. Any thoughts on how this should be
  done? I have a few, none of them appealing.

- Another problem I encountered is stuff within the jit (check.cpp and
  linear-scan.cpp) treating rVmSp and rVmFp specially, even though these
  are x64-specific. I want to try putting those in the X64 namespace,
  so that genuinely x64-specific usage sites have to be explicit about
  it, and then having runtime-populated rVmFp and rVmSp globals that
  depend on the current arch() for usage sites that don't care about
  platform.

- Made the IR printing stuff able to pretty-print ARM regs.

Reviewed By: @edwinsmith

Differential Revision: D1100519
2013-12-17 13:59:06 -08:00
Abel Nieto a1693289e2 Improve warning message in Set::toArray()
Array has a weird behaviour where string keys that can be represented
as ints are automagically converted to ints. From the manual:

  A key may be either an integer or a string. If a key is the standard
  representation of an integer, it will be interpreted as such (i.e.
  "8" will be interpreted as 8, while "08" will be interpreted as "08").

Since Set can contain both ints and strings, we could have e.g.

  $s = Set {1, '1'}

Calling $s->toArray() gives back then a 1-element array.

We were previously raising a warning in this case, but the warning didn't
specify what was the value of the "duplicate" key. Do so.

Reviewed By: @jdelong

Differential Revision: D1096274
2013-12-17 13:59:05 -08:00
Alexander d91fae6ae5 Add second parameter to nl2br
Adds the optional second `is_html` boolean parameter to match the Zend
implementation. The nl2br function still needs some work to have full
parity with zend, so the zend testcases aren't moved from bad to good
yet.

Reviewed By: @JoelMarcey

Differential Revision: D1101855

Pulled By: @scannell
2013-12-17 13:59:05 -08:00
Eugene Letuchy b8071aa339 add try/finally to NEWS
... it was the last major missing piece for 5.5 compat

Reviewed By: @ptarjan

Differential Revision: D1100828
2013-12-17 13:59:04 -08:00
bsimmers 666f330228 Kill MISOFF, rename HHIR_MISOFF to MISOFF
Reviewed By: @bertmaher

Differential Revision: D1100593
2013-12-17 13:59:04 -08:00
Rohit Bhoj 6f3c8c46b2 Modified findSingleTraitWithMethod so that it raises an error when there is trait collision for a trait alias
Modified findSingleTraitWithMethod so that it raises an error when there is trait collision for a trait alias

Reviewed By: @jdelong

Differential Revision: D1098140
2013-12-17 13:59:04 -08:00
Eugene Letuchy c1c06452a7 object data clone flags: handle c++ clone + php __clone
subclasses of c++ builtins (aka datetime) need to execute
 both the builtin's clone *and* whatever the PHP classes' __clone is.
 This unbreaks three datetime related test failures (my bad).

Reviewed By: @sgolemon

Differential Revision: D1102148
2013-12-17 13:59:03 -08:00
Eugene Letuchy c8605fa906 get rid of ObjectData::HasCppClone flag...
... by replacing it with the combination of IsCppBuiltin and
 HasClone. This frees up an ObjectData flags slot.

Reviewed By: @jdelong

Differential Revision: D1100574
2013-12-17 13:57:08 -08:00
Owen Yamauchi 86f5c0d1a6 Change vixl's internal stack pointer constant
This was a little tricky. On ARM machines, register number 31 is the
stack pointer. However, in some encodings, register number 31 refers to
a virtual "zero" register (basically the /dev/zero of registers). To
make sure that you don't accidentally use the wrong one with the wrong
encoding, vixl uses register number 63 to identify the stack pointer
(does not exist in hardware) and converts it to 31 while assembling.

This means that vixl uses 33 different register codes, so I'm changing
PhysReg to reflect this. This means we can now only represent 31 SIMD
register on ARM. I think this is preferable over losing the stack
pointer / zero register distinction in vixl.

Reviewed By: @edwinsmith

Differential Revision: D1100167
2013-12-17 10:30:30 -08:00
bsimmers 5a6d2d5254 Eliminate a couple linear searches in PGO mode
Instead of walking the entire list of profiling translations, keep
sets keyed on FuncID.

Default to JitRegionSelector=hottrace when JitPGO=true.

Reviewed By: aravind

Differential Revision: D1101198
2013-12-17 10:30:30 -08:00
Guilherme Ottoni 39800bb2bd Stop generating profiling translations after a threshold
This limits the duration of profiling, and skips PGO on functions
that aren't really hot.

Reuses the request count used to control the interpreter warmup
requests.

Reviewed By: @bertmaher

Differential Revision: D1095115
2013-12-17 10:30:29 -08:00
Drew Paroski d0a1138dfc Fix a typo in Map::differenceByKey()
Thanks to @Alite404Exception for catching this.

Reviewed By: @ptarjan

Differential Revision: D1101336
2013-12-17 10:30:29 -08:00
Bert Maher 3a79ee09a7 Changing some identifiers to make more sense.
Some trivial cleanup; it's pretty confusing to have a Value
named "state" when there is also a "struct State" in this file.

Reviewed By: @swtaarrs

Differential Revision: D1091303
2013-12-17 10:30:29 -08:00
Joel Marcey 8aef29cfcd Revisit how we handle post test information
All of our current local cronjob problems (not sure about chronos) are coming from corrupted .stat files. This is because the way we handled the gathering and printing of post test error information and stats were not 100% correct.

This diff hopefully helps fix this such that our local cronjob won't fail any longer.

Reviewed By: @ptarjan

Differential Revision: D1100647
2013-12-17 10:30:28 -08:00
Drew Paroski 352f5e479b Refactor bytecode emitter support for try/finally
This diff refactors the bytecode emitter support for try/finally. I re-
worked the algorithms to be written in an iterative manner (before they
were recursive) and fixed two small bugs, but aside from that I tried to
preserve the existing algorithms for now and mainly focus on moving the
code around and simplifying the structure a bit.

A lot of the emission logic for supporting try/finally was in separate
classes instead of EmitterVisitor which made things a bit unwieldy. This
diff takes most of the logic from FinallyRouter and FinallyRouterEntry and
moves it to EmitterVisitor, which helped simplify things and better fits
the style of the rest of the emitter. I got rid of the FinallyRouter class
and moved its fields to EmitterVisitor, and I renamed FinallyRouterEntry
and Action to "Region" and "ControlTarget" respectively. I also refactored
things a bit to reduce the amount of code that needs to deal with Regions.
Finally, I fixed a small bug where Region::getCaseCount() was double
counting the number of continue cases, and I improved the emitter to avoid
emitting a jump after the body of a try block when its not needed.

Ideas for future improvements: (1) simplify the algorithms and data
structures, (2) clean up how regions are created, entered, and left,
(3) merge the "Region" abstraction together with other region-like
concepts ("ForeachIterGuard", "FPIRegion", etc).

Reviewed By: @hermanventer

Differential Revision: D1099687
2013-12-17 10:30:28 -08:00
Drew Paroski 48580b3c5d Update NEWS file for the "Burrito" release
Reviewed By: @ptarjan

Differential Revision: D1100955
2013-12-17 10:30:27 -08:00
Eugene Letuchy 47a6dc08ab collections: unify collection object data flags
... the flags should all be the same. Fixes an inline issue
where FrozenSet was not marked as having a Clone function,
and *Vector and *Set were not marked as `IsCppBuiltin`.

Reviewed By: @jdelong

Differential Revision: D1100505
2013-12-17 09:37:15 -08:00
bsimmers 55d0bc9c50 Remove a couple 'using namespace' declarations from headers
Reviewed By: @ptarjan

Differential Revision: D1100100
2013-12-17 09:37:07 -08:00
bsimmers 03c020278d Don't put null/false in the json we pass to the test runner
It doesn't like that. It's going to be fixed to not barf on None, but
this will make things strictly better.

Reviewed By: @ptarjan

Differential Revision: D1100177
2013-12-17 09:37:03 -08:00
Sara Golemon 3dbe686d5a Add INI generator and generated files
Differential Revision: D1100639
2013-12-16 14:52:14 -08:00
Paul Tarjan d5deb150f4 make valgrind work
It doesn't always give us 4 bit aligned memory

Reviewed By: @edwinsmith

Differential Revision: D1060964
2013-12-16 13:03:11 -08:00
Edwin Smith 2e7414f1cb Fix RegSet::size() so it counts all the bits
builtin_popcount() silently truncated to int.

Reviewed By: @oyamauchi

Differential Revision: D1100154
2013-12-16 13:03:07 -08:00
bsimmers ac954c4d74 Disable flaky zend test
Reviewed By: @bertmaher

Differential Revision: D1100222
2013-12-16 13:03:04 -08:00
Emil Hesslow c8001cc9ed Fixes to parse_ini_(file|string)
Do a bunch of fixes in the parse_ini lexer and parser

Closes: #1320
Closes: #825
Closes: #838

Reviewed By: @ptarjan

Differential Revision: D970513
2013-12-16 13:03:01 -08:00
Paul Tarjan 782913bb47 fastcgi headers need unmangling
Headers as mangled in the FastCGI protocol, but the `getHeader()` method on `Transport` assumed the header was the original value.

Closes #1359

Reviewed By: @alexmalyshev

Differential Revision: D1098954
2013-12-16 13:02:57 -08:00
bsimmers e39ab52b12 Fold HPHP::Transl's contents into HPHP::JIT
Reviewed By: @ptarjan

Differential Revision: D1099088
2013-12-16 13:02:53 -08:00
Drew Paroski d926bdf746 Fix how the bytecode emitter handles foreach loops inside fault funclets
The bytecode emitter had a bug where it wasn't properly keeping track of
which iterators were live at a fault funclet's entry point. When emitting
a foreach loop inside the body of a fault funclet, the bytecode emitter in
some cases would erroneously use an iterator variable ID that was already
live.

This diff fixes the bug by updating the bytecode emitter to keep track of
which iterators were live at a fault funclet's entry point, and by updating
the logic for allocating iterator variable IDs to correctly handle foreach
loops inside fault funclets.

Reviewed By: @jdelong

Differential Revision: D1099508
2013-12-16 13:02:49 -08:00
Drew Paroski 1610575159 Improve c_Map::reserve
This diff tightens up the logic in c_Map::reserve to be more careful when
mixing signed and unsigned integers and when mixing 32-bit and 64-bit
integers.

This diff also removes a bogus assert, adds some more (non-bogus) asserts,
and adds some comments.

Reviewed By: anietoro

Differential Revision: D1097684
2013-12-16 13:02:46 -08:00
Jordan DeLong 780baaf33e Minor const correctness fix in hhbc.{h,cpp}
Reviewed By: @alexmalyshev

Differential Revision: D1094436
2013-12-16 13:02:42 -08:00
Jordan DeLong fec7562974 Make IterRange work with range-based for
Give it a begin() and end() function.

Reviewed By: @edwinsmith

Differential Revision: D1093982
2013-12-16 13:02:38 -08:00
Jordan DeLong c6c2ad63a2 Fix a bug in return type inference: ctors can be inherited from abstract classes
I think I was thinking that since interfaces can't declare
__construct methods, abstract classes probably couldn't either.
Actually not true.

Reviewed By: @dariorussi

Differential Revision: D1092876
2013-12-16 13:02:35 -08:00
bsimmers 29d0171824 Disable flaky zend test
Reviewed By: @jdelong

Differential Revision: D1099379
2013-12-16 13:02:31 -08:00
bsimmers f65f1d3b8a chmod -x runtime/vm/jit/*.{cpp,h}
I don't know why this keeps happening.

Reviewed By: @jdelong

Differential Revision: D1098912
2013-12-14 13:19:42 -08:00
Jan Oravec bcc10cbd48 Pass inGenerator flag in RetCtrl and FunctionExitSurpriseHook
Code gen for FunctionExitSurpriseHook and refcount optimization RetCtrl
opcode processing needs to know whether these opcodes were used inside a
generator. They currently obtain this information thru curFunc(). This
information is known statically, so pass it explicitly.

Needed for unified inner/outer generator functions.

Reviewed By: @jdelong

Differential Revision: D1095196
2013-12-14 13:19:39 -08:00
Owen Yamauchi 28149540e1 Make PhysReg able to represent 64 registers
Finally. PhysReg can now represent 32 GP regs and 32 SIMD regs.

Having the arch() dependency inside PhysReg feels a little strange, but
(a) Map really does need to behave differently depending on the
architecture, and (b) it's really convenient to have Map defined inside
PhysReg. I think it's an okay tradeoff.

In a followup diff, I'll get rid of x2a and have PhysRegs with ARM
register numbers flowing through XLS. It's still going to be a bit messy
because both codegen backends use the operator[] trick to create memory
references from register + offset. The ARM backend uses
vixl::Register::operator[], but the x64 backend uses
PhysReg::operator[]. I'm not yet sure how I'll reconcile this.

Reviewed By: @ottoni

Differential Revision: D1097959
2013-12-14 13:19:36 -08:00
Joel Marcey 68a39435b6 Make the user run command output better
The way I was generating the "RUN TEST FILE" commands at the end of the script run or within .errors/.fatals files was not the best. This improves that.

Reviewed By: @ptarjan

Differential Revision: D1098631
2013-12-14 13:19:32 -08:00
Joel Marcey 4350e9f04c Sigh. More post test warning fun for yii.
I love yii. I love yii. I love yii.

Need to check for another type of post test warning, that includes a PHPUnit Exception.

Reviewed By: @ptarjan

Differential Revision: D1098761
2013-12-14 13:19:29 -08:00
Alok Menghrajani 9f38afda2a Refactor func.h
Reviewed By: @paroski

Differential Revision: D1075910
2013-12-14 13:19:25 -08:00
Joel Marcey d3b2dfed63 Check for post test warnings too.
It looks like we fixed the post test fatal problem that joomla was having, but now yii may have post test warnings. For example,

/data/users/ptarjan/fbcode/hphp/test/frameworks/frameworks/yii/tests/./
framework/web/auth/CWebUserTest.php
HipHop Warning: Constant PHPUNIT_COMPOSER_INSTALL already defined in ve
ndor/phpunit/phpunit/composer/bin/phpunit on line 49

Let's see if this can fix that.

Reviewed By: @alexmalyshev

Differential Revision: D1098415
2013-12-14 13:19:22 -08:00
aravind 0d47329a8a Add support for IsScalar
Add support for IsScalar in IsType instruction.

Reviewed By: @ptarjan

Differential Revision: D1087810
2013-12-14 13:19:18 -08:00
Owen Yamauchi a54339ed27 Delete PhysReg::operator int()
With this, I think the dependency is broken, and we can start using
PhysReg to represent different register sets smoothly, without wrecking
anything.

Reviewed By: @edwinsmith

Differential Revision: D1096506
2013-12-14 13:19:14 -08:00
Abel Nieto bc922ca72a Move collections into their own namespace (Vector)
We want external developers to be able to use their own collection classes (e.g. Vector, Map, etc.) without colliding with HHVM's native versions.

This diffs moves the Vector class to the HH namespace.

It uses the "autoimport" mechanism in the parser so that the change is mostly transparent to PHP-land, and also modifies the IDL compiler so that class names (in the IDL) can contain namespaces.

i.e. for Vector, we change the class name in the IDL from "Vector" to "HH_Vector", which later gets exported as "HH\Vector" in PHP-land.

Reviewed By: @paroski

Differential Revision: D979471
2013-12-14 13:19:11 -08:00
Owen Yamauchi b9332084ff Make PhysReg(int) private to RegSet
The two register allocators had some remaining offenders. XLS was really
easy to fix (and in fact it made the code nicer), whereas LinearScan
didn't want to go quietly.

There is one substantive difference: in the stress mode where LS has a
reduced number of free registers, the ones at the beginning of the
sequence will be reserved instead of at the end. I could have avoided
that by giving PhysReg::Map a reverse iterator, but I don't think it
matters that much.

Up next: remove PhysReg::operator int().

Reviewed By: @edwinsmith

Differential Revision: D1096303
2013-12-14 13:19:07 -08:00
Sara Golemon 03e0826d77 Add ICU's IntlTimeZone and IntlIterator classes
Per zend implementation

Reviewed By: @ptarjan

Differential Revision: D1085605
2013-12-13 12:39:28 -08:00
Sara Golemon 1ba8fe784a Use ZendParamMode for all HNI methods
Removes method prologue as unnecessary since
we're coercing types during the call anyway.

Fixes fileinfo's HNI declarations to use nullable types.

Reviewed By: @ptarjan

Differential Revision: D1096599
2013-12-13 12:39:27 -08:00
Sean Cannella deb7d47f38 Fix Redis typo
Fix redis typo

Closes #1341

Reviewed By: @JoelMarcey

Differential Revision: D1097766
2013-12-13 12:39:27 -08:00
Joel Marcey d7ff0c33fa Append to the _script.errors file during a run of the script
Append to _script.errors during a single run of the script in case different frameworks have script errors during an --all run, for example.

Reviewed By: @ptarjan

Differential Revision: D1097486
2013-12-13 12:39:27 -08:00
Joel Marcey f620c88d24 Avoid post test fatals from getting in the way of stats
This diff should hopefully help the cronjob run better.

The cronjob and my local runs were getting errors like this:

The stats file for joomla is corrupt! It should only have test names and statuses in it.

We were getting this because of hhvm cleanup core dumps, etc. after a test was run. Instead of printing stats in the stats file, we were printing this fatal information, which corrupted the stats file.

So, I captured this fatal information and directed it to the fatals file instead.

Reviewed By: @ptarjan

Differential Revision: D1097602
2013-12-13 12:39:26 -08:00
Owen Yamauchi c6b4136ac7 Rewrite reg-algorithms.h to not use PhysReg(int)
I'm trying to break dependencies on PhysReg's internal representation
(regnum for GP regs; regnum + constant offset for SIMD regs). This is
necessary to use it for ARM registers. This means forbidding direct
conversion between int and PhysReg, and this file is one of the worst
offenders.

I rewrote it to use PhysRegs everywhere (this doesn't ruin the compiled
code; PhysReg's only member is an int so passing it around by value
and copying it isn't a big deal), and in the process introduced
PhysReg::Map, which uses the convenient underlying representation to be
compact, but hides that detail behind an STL-like container interface.

The next step will be to flush out other places where implicit
int-PhysReg conversion happens, and squish it. Once it's all gone, we
can freely mess around with the internal representation of PhysReg, and
it will all be contained in PhysReg, PhysReg::Map, and RegSet.

Reviewed By: @edwinsmith

Differential Revision: D1095930
2013-12-13 12:39:26 -08:00
mwilliams 6b84e33b74 Fix bug in side exit code
The code to detect a side exit to the first instruction in the
tracelet was broken for inlining, if the offset of the side-exiting
instruction just happened to be the same as the offset of the start
of the tracelet.

If we're inlining, we know they're not the same though, so skip the
check in that case.

Reviewed By: @jdelong

Differential Revision: D1096829
2013-12-13 12:39:25 -08:00
Alok Menghrajani 3ab63633b8 Always log soft/nullable type failures.
At this point, we want a way to always log these type warnings in the runtime (instead of the current 1/100 sampling). The next
step is to convert the nullable warnings into exceptions (see 83c970e1d8c01fd6e20c2cdb32d6a047c79edc4d).

Reviewed By: @paroski

Differential Revision: D1068880
2013-12-13 12:39:25 -08:00
Alex Malyshev ad81b7fe09 Fix incorrect condition in libmagic
File::seek returns true/false as a success status, so don't compare it
against a size_t.

Clang also doesn't like using an assignment in the condition of a
for-loop, wrapping it in parens silences the warning.

Reviewed By: @scannell

Differential Revision: D1096987
2013-12-13 12:39:25 -08:00
Alex Malyshev 312908509d Account for other libelf implementations
Turns out that there's at least two implementations of libelf,
one at http://www.mr511.de/software/english.html, and the other at
https://fedorahosted.org/elfutils/. One of them has elf_getshstrndx
return 0 on success, and the other returns 1.

Reviewed By: @scannell

Differential Revision: D1095441
2013-12-13 12:39:24 -08:00
Sean Cannella 5f739556de Add request-based override for HHProf profile mode
Adds the ability to override the runtime option specifying
allocation vs. heap profile on a per-request basis by adding profileType=foo to
the query string specified in the HHProf start request.

Reviewed By: @edwinsmith

Differential Revision: D1096216
2013-12-13 12:39:24 -08:00
Alex Malyshev d3946cdd14 Mark variable as unused
It's even called _unused...

Reviewed By: @jdelong

Differential Revision: D1096686
2013-12-13 12:39:23 -08:00
Edwin Smith a3c8c88b16 XLS support for SIMD registers.
Adds a simd field to Abi, plus code to have allow & prefer
sets for each interval.  We try to allocate from the prefer
set, but always at least take from the allow set.  Doubles
always prefer simd.  In addition, instructions that load and
store Cells, prefer simd.  This mimics the existing policy in
linear-scan.cpp.

Also changes linear-scan.cpp to not prefer GPRs for a tmp
that is an XMM candidate but which crosses a native call,
when HHIREnableCalleeSavedOpt==false (since prefering GPRs
in that case is part of the optimization).

Add support for XMM registers to PhysRegSaver.  If we had
a live XMM (double or TypedValue) that spanned a call, it
wasn't getting saved.

Reviewed By: @ottoni

Differential Revision: D1091845
2013-12-13 12:39:23 -08:00
bsimmers 40d446b9ce Misc cleanup
Simplify some IRTrace creation logic and clean up some type
smart::unique_ptr code now that we're on gcc >=4.7.

Reviewed By: @jdelong

Differential Revision: D1079241
2013-12-13 12:39:23 -08:00
Drew Paroski 2d7d6ccbe3 Fix bogus asserts in c_Map's implementation
There were two erroneous asserts in c_Map's implementation that were failing
in some cases when elements in a Map were unset. This diff removes the bogus
asserts.

Reviewed By: @dariorussi

Differential Revision: D1096926
2013-12-13 12:39:22 -08:00
Herman Venter f7fe29dcaf The PHP code model uses sourceLocation rather than location for the name of the source location property
Fixed the VM AST to Code Model serializer to use "sourceLocation" rather than "location". Also fixed the serialization of constant expressions to use "variableName" rather than just name and to use the original name field for its value. Also fixed serialization of closure expressions to check for the case where there are no captured variables.

Reviewed By: duv

Differential Revision: D1095904
2013-12-13 12:39:22 -08:00
Joel Marcey 15db67d0bc Stop being an error() clown.
@ptarjan's cronjob brought about an error that looked like this:

HipHop Warning: error() expects exactly 1 parameter, 0 given in /data/users/ptarjan/fbcode/hphp/tools/command_line_lib.php on line 16
HipHop Fatal error: Argument 1 passed to error() must be an instance of string, null given in /data/users/ptarjan/fbcode/hphp/tools/command_line_lib.php on line 16

Well, that is because error() requires a string as a parameter and there were cases in --csv where I called error() without a string.

Why the error is happening, we can hopefully find out after this fix too.

Fixed that. Actually re-did the erorr handling just a tad.

Reviewed By: @alexmalyshev

Differential Revision: D1096625
2013-12-13 12:39:21 -08:00
Guilherme Ottoni 36b0ee227a Always spill the stack before conditional jumps
This enables more opportunities to smash the jump in 'a', thus
avoiding going through astubs.

Reviewed By: @swtaarrs

Differential Revision: D1095483
2013-12-13 12:39:21 -08:00
Abel Nieto fb5de5ea8b Add unimplemented collection functions
There were a bunch of collection-related functions (e.g. collectionSet()) that
FrozenVector didn't implement. Fix that.

Reviewed By: @paroski

Differential Revision: D1066321
2013-12-13 12:39:21 -08:00
Guilherme Ottoni 354f0bdcfd Reduce JitPGOThreshold to 4
This seems to avoid some of the overhead for profiling and
retranslating in perflab.  It's possible that we can benefit from
additional profiling data, but this lower threshold seems to be the
best for perflab right now.  We can revisit it once we can increase
perflab warmup.

Reviewed By: aravind

Differential Revision: D1093148
2013-12-13 12:39:20 -08:00
Alex Malyshev 25f3c76b2a Fix errors reported by clang-3.4
Fix ArrayData's protected member m_kind being accessed incorrectly

Clang didn't like having a static_assert in an anonymous struct in
an anonymous union.

Seems like objects that use the new member initialization syntax are
required to have a user defined ctor, at least that's what the error
was...

Reviewed By: @jdelong

Differential Revision: D1093761
2013-12-13 12:39:20 -08:00
Alex Agape 7f31c17ea9 empty product return 1
Changed the return from 0 to 1.

Reviewed By: @ptarjan

Differential Revision: D1079222
2013-12-13 12:39:20 -08:00
Paul Tarjan cd4748908e fix a bunch of output buffering things
phpmyadmin (ab)uses this quite a bit and we are grossly incompatible. Either PHP has changed a bunch since 5.2 or the original author didn't test it thoroughly.

Reviewed By: @alexmalyshev

Differential Revision: D1095350
2013-12-13 12:39:19 -08:00
Alex Malyshev 4b032a8df6 Replace typeof with decltype
typeof is a GCC extension but decltype is part of the standard

Reviewed By: @jdelong

Differential Revision: D1095111
2013-12-13 12:39:19 -08:00
Alex Malyshev ddb294278b Remove unused function.
There's a dupe of this function in ext_mysql.cpp, but that one
actually gets used.

Reviewed By: @ptarjan

Differential Revision: D1095189
2013-12-13 12:39:18 -08:00
Sandeep Bindal bd6e62bee1 Namespaces should complain on double use
Fixed the double use problem

Reviewed By: @ptarjan

Differential Revision: D1091074
2013-12-13 12:39:18 -08:00
Drew Paroski fdc5e1b903 Update Map to use HphpArray-like data structure
This updates Map to use an HphpArray-like data structure instead of the old
data structure it was using. As a consequence Maps will now retain insertion
order.

With this change, Map performance stayed the same or improved on several
micro-benchmarks that test out different aspects of Map performance (such
as foreach, creating lots of small maps, building large maps, accessing
using "$c[$k]" syntax, etc).

Reviewed By: anietoro

Differential Revision: D1085607
2013-12-13 12:39:18 -08:00
Alex Malyshev e09620554c Fix unused variable
Actually use it instead.

Reviewed By: @jdelong

Differential Revision: D1094345
2013-12-13 12:39:17 -08:00
Herman Venter ee89706f31 Eliminate dead code from parser
The parser has a mechanism for creating a list of statements that are prepended to the next statement added to the main list of statements. This code is completely dead and serves only to confuse the reader.

Reviewed By: @jdelong

Differential Revision: D1093564
2013-12-13 12:39:17 -08:00
Alex Malyshev 7923afb3ed Fix uninit variable
All in the title.

Reviewed By: @jdelong

Differential Revision: D1094123
2013-12-13 12:39:16 -08:00
Alex Malyshev 4fcfb3a0de Call uninit_null() instead of using it as a fn pointer
This doesn't return an uninit null, it casts the function
pointer 'uninit_null' to a bool, which then gets cast
to a Variant "true". Don't you just love PHP I mean C++.

Reviewed By: @jdelong

Differential Revision: D1093730
2013-12-13 12:39:16 -08:00
bsimmers aa51a2837c Properly loosen refcount opts assert
My previous attempt at this solved the specific problem I was looking
at but accidentally tightened up the assert in a place it shouldn't be
checking. This diff fixes that and improves the stacktrace file for one of the
failure cases.

Reviewed By: @ptarjan

Differential Revision: D1093847
2013-12-13 12:39:16 -08:00
Alex Malyshev bcdfa958c3 Handle 'encoding' argument for get_html_translation_table
We were ignoring it previously, and just using the default encoding.

Reviewed By: @ptarjan

Differential Revision: D1092741
2013-12-13 12:39:15 -08:00
Abel Nieto 1a8a4e2f1b Make FrozenSet a collection.
Flip the switch and make FrozenSet a full-blown collection.

This wires up support for literal syntax, casting to bool,
and materialization and magic methods.

Reviewed By: @elgenie

Differential Revision: D1060075
2013-12-13 12:39:15 -08:00
Paul Tarjan 6e2310dfd7 import skipif sections from zend tests
We've been working around various issues (the win32 tests, many of the blacklists) where the tests were actually telling us in what cases they shouldn't be run.

Very few tests actually pass now but I think this is the right thing to do

Reviewed By: @alexmalyshev

Differential Revision: D983880
2013-12-13 12:39:06 -08:00
Jan Oravec 82eebe1104 Fix warning with tvSet(make_tv<KindOfNull>(), dst)
make_tv<KindOfNull>() creates a temporary TypedValue with uninitialized
m_data field. Using this temporary together with tvSet() results in a
warning, as the uninitialized value is assigned the destination's m_data
field.

Introduce tvSetNull() that avoids touching m_data.

Reviewed By: @jdelong

Differential Revision: D1090898
2013-12-13 11:21:04 -08:00
Paul Tarjan 2d4f9ee46b use same PHP Object for the same xmlNode
Instead of using the `_private` like zend does, I'll just have a thread local map on the side. I'm a bit worried that `_private` is used by other places so this seems safer and easier to reason about.

Reviewed By: @alexmalyshev

Differential Revision: D1071499
2013-12-13 11:20:59 -08:00
Paul Tarjan 3c97357707 blacklist bug36999
Broken on travis witha  SoapFault which I know nothing about.

Reviewed By: @scannell

Differential Revision: D1093510
2013-12-13 11:20:54 -08:00
Edwin Smith 5ff2e63748 Convert IRTrace::m_blocks from std::list to smart::vector
Use smart::vector instead of std::list in IRTrace

Reviewed By: @swtaarrs

Differential Revision: D1077237
2013-12-13 11:20:49 -08:00
Sara Golemon 965441c12e Ignore this test in the OSS build (for now) 2013-12-12 20:03:28 -08:00
Sara Golemon 2084216639 Skip tests when we don't have enough gd support
Also enable imagerotate() in OSS build.
2013-12-12 20:03:28 -08:00
Sara Golemon 52158dfb0c No longer look for GD, it's now bundled.
Instead look for its optional dependencies
* libfreetype
* libjpeg
* libpng
* libvpx
2013-12-12 20:03:28 -08:00
Owen Yamauchi bbbd10db4f Massage vixl's register abstractions into shape
The thesis of this diff is to introduce implicit conversions between
vixl::CPURegister and PhysReg, the same way we have for the x64 register
classes.

- I removed the concept of "no register" from vixl. It overlaps with
  "invalid register" and was kind of confusing.

- constexpr all the things

- Add the implicit constructor and conversion operator to PhysReg

I considered making the vixl abstractions mirror the asm-x64
abstractions exactly -- i.e. get rid of the class hierarchy -- but that
would be too disruptive. I think this is all we'll need to do.

I also haven't made implicit conversions between PhysReg and
vixl::FPRegister yet. We still need to sort out the way PhysReg
represents SIMD registers internally (changing the number of GP regs
isn't as simple as changing that constant) but that can be done in a
future diff.

Reviewed By: @edwinsmith

Differential Revision: D1091795
2013-12-12 20:03:28 -08:00
Edwin Smith f893fa2f14 Rename XMM to SIMD in a bunch of places to remove x86 smell
Trying to limit the term XMM to x86-specific code.  Everywhere
else we'll refer to SIMD registers.

Reviewed By: @ottoni

Differential Revision: D1091895
2013-12-12 20:03:28 -08:00
Drew Paroski 7193f48b48 Change the HHBC spec as needed to support the mechanics of try/finally
Reviewed By: @edwinsmith

Differential Revision: D1092390
2013-12-12 20:03:28 -08:00
mwilliams 1159ed5044 Generate a pid.map file when we unmap parts of the text section
The perf tool won't lookup symbols for parts of the binary
that aren't file mapped, so provide a perf-pid.map file when we
do that.

Reviewed By: @bertmaher

Differential Revision: D1091918
2013-12-12 20:03:28 -08:00
Paul Tarjan c825b734c6 ini_get('date.timezone') shouldn't guess
It should only return the timezone that was expclitily set.

Reviewed By: @JoelMarcey

Differential Revision: D1091812
2013-12-12 20:03:27 -08:00
Paul Tarjan 00ca68a715 import libgd from zend
I tried puling in the real `libgd` but it turns out php-src forked the library pretty hard and didn't contribute back. Instead I'll just pull in their fork.

This is a straight copy and then I fixed all the stupid C -> C++ stuff and wrote the `php_compat.h` to shim.

Reviewed By: @alexmalyshev

Differential Revision: D1083759
2013-12-12 20:03:27 -08:00
Paul Tarjan 668d434066 Fill out NEWS for some old releases a bit
I went throught the tasks for the last few releases and put down some things. Can anyone else notice other big things in your releases? I still have to fill out all the OSS stuff in Mark's but they are all on stickeys at the office.

Reviewed By: @jdelong

Differential Revision: D1091115
2013-12-12 20:03:27 -08:00
Max Wang 0301cbc29c Push KindOfStaticString TV in String opcode
Currently, we're pushing a KindOfString static StringData TV; let's use
KindOfStaticString instead.

Reviewed By: @jano

Differential Revision: D1090934
2013-12-12 20:03:27 -08:00
Guilherme Ottoni 82e971d73c Simplify instructions before looking them up in the CSE hashtables
I noticed some cases where CSE was missing opportunities because we
were first checking the CSE hashtable, then simplifying the
instruction (when missing in the CSE hashtable), and finally inserting
it into the CSE hashtable.  For instructions that actually got
simplified, this ordering caused redudant instructions to miss in the
CSE hashtable.  This diff fixes the problem by changing the order so
that instructions are first simplified, and then inserted in the
hashtable.

Reviewed By: @edwinsmith

Differential Revision: D1086429
2013-12-12 20:03:27 -08:00
Guilherme Ottoni 42be9c5853 Add contbuild config to run tests with hottrace regions
That's it.

Reviewed By: @swtaarrs

Differential Revision: D1086968
2013-12-12 20:03:27 -08:00
Guilherme Ottoni b2a9c02f22 Disable specialized type guards when guard relaxation is off
Otherwise we end up specializing way too many things, most for no use.

Reviewed By: @swtaarrs

Differential Revision: D1088082
2013-12-12 20:03:27 -08:00
Paul Tarjan 48c5e8cbbf sometimes the random variance is high
I've seen this test fail a few times since the variance on the random number generator is pretty high. Add some wiggle room.

Reviewed By: @jdelong

Differential Revision: D1091124
2013-12-12 20:03:26 -08:00
ptarjan 0a0b16c564 bump version for next dev release 2013-12-12 15:26:23 -08:00
Paul Tarjan 050c081b0e make rename_variation parallelizaable
Reviewed By: @JoelMarcey

Differential Revision: D1091010
2013-12-10 17:39:34 -08:00
Paul Tarjan f60871951a fix afile
Reviewed By: @andralex

Differential Revision: D1091032
2013-12-10 17:39:30 -08:00
Alex Malyshev 3ea5f063f1 Implement GlobIterator
Required changing the behavior of DirectoryIterator and
FilesystemIterator. DirectoryIterator should iterate through the base
names of files, but FilesystemIterator iterates through full
pathnames.

Fix a bug in RecursiveIteratorIterator along the way

Reviewed By: @ptarjan

Differential Revision: D1034196
2013-12-10 17:39:29 -08:00
Paul Tarjan 6650bf347b fix more vfprintf
Reviewed By: @JoelMarcey

Differential Revision: D1091125
2013-12-10 17:39:25 -08:00
Alex Malyshev a732e038ed Add the Reflection class
We never defined the actual Reflection class, which just has two
static methods in it.

Appeases yii, which has a requirements check that determines whether
the Reflection extension is enabled by searching for this class.

Reviewed By: @ptarjan

Differential Revision: D1086615
2013-12-10 12:13:55 -08:00
Edwin Smith 024ef0aa29 Fix up the const-to-variant code
Several cases were doing it wrong.  Found them while auditing
implicit Variant constructors.

Reviewed By: @jdelong

Differential Revision: D1077928
2013-12-10 12:13:48 -08:00
Jan Oravec aa4cd4f6ad Use std::atomic<> for condition flags
Convert atomic_acquire_load and __sync_fetch_and_{and,or} on condition
flags to std::atomic<>.{load,fetch{and,or}}.

Reviewed By: @jdelong

Differential Revision: D1084266
2013-12-10 12:13:45 -08:00
Jan Oravec a100e2c3af Use std::atomic<> in TreadHashMap
Convert TreadHashMap from atomic_{acquire_load,release_store} to
std::atomic<>.{load,store}.

Reviewed By: @jdelong

Differential Revision: D1084196
2013-12-10 12:13:41 -08:00
bsimmers 75b2da18c1 Loosen refcount verifier on DefLabels
Sometimes we end up with a DefLabel that defines a value with type
Cell, but only has one incoming value with an uncounted type. The Cell dest of
the label won't have any tracked references since it's always uncounted, so
recognize that situation and don't abort.

Reviewed By: @ptarjan

Differential Revision: D1090701
2013-12-10 12:13:33 -08:00
Paul Tarjan 928cf31b83 remove unused code
Reviewed By: @alexmalyshev

Differential Revision: D1090454
2013-12-10 12:13:29 -08:00
mwilliams aa602c715c Fix read past end of buffer in IpBlockMap
The code used to allow a read of the bit immediately past
the end of the buffer - and since both children should be nullptr
in that case, the value doesn't matter. But its still an illegal
read, and the ASAN build was catching it.

Reviewed By: @edwinsmith

Differential Revision: D1089631
2013-12-10 09:33:01 -08:00
Paul Tarjan 05c3fa5efe fixup yaml to be c++ compliant
`fpermissive` is bad and we shouldn't set it

Reviewed By: @scannell

Differential Revision: D962946
2013-12-10 09:33:00 -08:00
Andreas Fischer a7146f2010 Typo: compatability -> compatibility (II)
Typo: compatability -> compatibility (src)

Closes #1328

Reviewed By: @edwinsmith

Differential Revision: D1089152

Pulled By: @scannell
2013-12-10 09:33:00 -08:00
Jordan DeLong f8e0acd947 Improve printing of ?Obj types
Reviewed By: @edwinsmith

Differential Revision: D1088697
2013-12-10 09:33:00 -08:00
Jordan DeLong 3304d86ba1 Relax bytecode invariants about DV initializers
DV initializers had some rules about fallthrough, jumps to
the main entry point, and a requirement that they each only be a basic
block.  We violate these rules in array_filter.hhas and
array_map.hhas, and they currently don't seem to be needed.  This
changes the spec so they are just alternative entry points based on
argument count, and updates hhbbc to not assume those things.  We
still have a few reasonable rules about where the entry points can be
(they must be in the primary function body, and cannot be in the
middle of an FPI region).

Reviewed By: @edwinsmith

Differential Revision: D1088641
2013-12-10 09:32:59 -08:00
Jordan DeLong 0ca9862bd9 Add an hhas test case for DV initializers with fault/catch regions
From what I can tell, nothing rules this out in the bytecode
spec.  Wrote this to see if it actually worked, which it seems to.

Reviewed By: @edwinsmith

Differential Revision: D1010605
2013-12-10 09:32:59 -08:00
Jordan DeLong 4e97ca67fb Propagate states across factored edges mid member-instruction
Member instructions are fairly unusual in that they can throw
with a state reflecting changes in the middle of their execution.  The
normal model in HHBBC for PEIs (potentially exception-throwing
instructions) is to propagate the state before the instruction has
begun execution, so these need to be handled specially by explicitly
propagating the states before each dim.

Reviewed By: @edwinsmith

Differential Revision: D1088633
2013-12-10 09:32:58 -08:00
Jordan DeLong 168d6fc15b Use getScalarValue instead of ad hoc cases for scalar array pairs
Reviewed By: @markw65

Differential Revision: D1024221
2013-12-10 09:32:58 -08:00
Owen Yamauchi 6f98d64c3c Speed up simulator's register-smashing code
I feel bad, because I wrote this originally. perf showed that this code
was really hot, so I rewrote it much simpler. I also fixed some mistakes
in the register-convention constants provided by vixl. This seems a
little wtf, but what they had there before definitely doesn't agree with
the documentation, as well as the implementation of
vixl::CPURegList::GetCallerSaved.

Reviewed By: @jdelong

Differential Revision: D1087062
2013-12-10 09:32:58 -08:00
Chip Turner b20473bf84 Re-introduce MySQL 5.6 client
This reverts e5cdbb1a67f28f94d43c83ff2627fd3eff8b3646 which
reverted the original 5.6 client update based on the issue from 3340526.
With third-party patched with D1088527 fixing the double-close, this
diff restores 5.6 to fbcode.

Original 5.6 diff: D1058111
Reverted in: D1087701
MySQL fixed in: D1088426
third-party patched in: D1088527

Reviewed By: jicongrui

Differential Revision: D1088758
2013-12-10 09:32:57 -08:00
Ryan Skidmore 078f8473b2 Fix typos (src)
Fix typos (src)

Closes #1329

Reviewed By: @edwinsmith

Differential Revision: D1089170

Pulled By: @scannell
2013-12-10 09:32:57 -08:00
Edwin Smith 132526bdc3 Parameterize XLS with a register abi descriptor.
Create an Abi POD struct that encapsulates details about the
ABI that the register allocator needs to know.  For now, it's
just what register are available to be allocated and which
ones are callee-saved registers.

Reviewed By: @jdelong

Differential Revision: D1088590
2013-12-10 09:32:57 -08:00
Simon Welsh 05650dc744 Pass the length along when outputting from printf
If there's no length, the result is treated as a
null-terminated string which means that null characters incorrectly stop
the output.

Closes #1322

Reviewed By: @ptarjan

Differential Revision: D1087212

Pulled By: @scannell
2013-12-10 09:32:56 -08:00
Paul Tarjan 37034dd221 Hook IniSetting::Bind to ini_get()
This started as a small diff to get `date.timezone` working and escalated to this.

I did it as a small change with just adding a get callback to the bind call and used it during the get. I debated having a side-index of everything that has been set so far and echo it back, but the setting might muck with the data before saving so I think this is more generic.

I think in a perfect world you could just register their name, type, and an optional validator, but that's for later when this gets cumbersome.

Reviewed By: @sgolemon

Differential Revision: D1088980
2013-12-10 09:32:56 -08:00
Paul Tarjan f745001876 update PCRE_VERSION
Stop lying. Symfony checks this and throws a warning saying we are too old when we aren't.

Reviewed By: @sgolemon

Differential Revision: D1088930
2013-12-10 09:32:56 -08:00
Paul Tarjan 35d153b6cd mark systemlib classses as \!isUserDefined()
I can't beleive we lived this long with this `if (false)`

Reviewed By: @alexmalyshev

Differential Revision: D1088081
2013-12-10 09:32:55 -08:00
Paul Tarjan f02ebaeb3c remove functions we don't implement
These fly completly in the face of the `function_exists` detection that you are supposed to use. The worse offender was a completly unimplement extension of image magic.

I ran `git grep` in `runtime/ext`

Reviewed By: @sgolemon

Differential Revision: D1088798
2013-12-10 09:32:55 -08:00
Paul Tarjan 1563cfd1d1 import files even if they have an ini section
I was lying a little bit and not importing these tests since they have no chance of passing since our INI story sucks. I think we shouldn't be cheating with our numbers and instead should have these and be able to work towards them passing.

Reviewed By: @JoelMarcey

Differential Revision: D1082559
2013-12-10 09:32:35 -08:00
Paul Tarjan 8bc5d66a14 ext_zend_compat improvements
These were brought on by importing `fileinfo`. I ended up doing it natively in HHVM, but these bugfixes are still useful. The worst part is the preg stuff since our code diverged so much from zend I had to just copy theirs. Some day we hopefully can reconcile them.

Reviewed By: @paroski

Differential Revision: D1025745
2013-12-09 18:44:01 -08:00
Ryan Skidmore 2ff6d3ca00 Fixed typos
Summary: Fixed typos

Reviewed By: @scannell

Pulled By: @scannell

Test Plan:
 - php -l and checkModule
 -
2013-12-09 07:22:23 -08:00
Andreas Fischer 7aee17cb65 Typo: compatability -> compatibility (I)
Summary: Typo: compatability -> compatibility (cmake)

Reviewed By: @scannell

Pulled By: @scannell
2013-12-09 07:01:50 -08:00
mwilliams beb2c83548 Don't eagerly start threads after warmup
If we've requested a warmup phase, we limit the number
of threads initially, and then allocate more after a suitable
warmup period.

We don't need to eagerly alloate them though - we can stick with the
existing code which only allocates as necessary.

Reviewed By: @jdelong

Differential Revision: D1087578
2013-12-08 10:33:28 -08:00
Jordan DeLong 4668713374 Disable some zend tests that are failing on master
Reviewed By: @dariorussi

Differential Revision: D1088692
2013-12-08 10:33:09 -08:00
Jordan DeLong b245336ea3 Taskify some TODOs for hhbbc
Made tasks; removed some comments.

Reviewed By: @edwinsmith

Differential Revision: D1088620
2013-12-08 10:30:18 -08:00
Jordan DeLong 67e991b0af There's no "if for" statement
This is for @alexmalyshev.

Reviewed By: @alexmalyshev

Differential Revision: D1088412
2013-12-08 10:30:15 -08:00
Jordan DeLong 4fa789a460 Fix a bug I had in AsyncAwait's hhbbc implementation
AsyncAwait pushes an HHBC "Cell" flavor, which corresponds to
the TInitCell type in HHBBC (it can't be KindOfUninit).  Oops.

Reviewed By: aravind

Differential Revision: D1088391
2013-12-08 10:30:12 -08:00
Jordan DeLong eabd6792b6 Update HHBBC fault funclet assumptions for try/finally changes
The main change is that fault funclets now can be coverted by
protected regions.  There were also some issues with having multiple
protected regions pointing to the same fault funclet, even though I'd
already updated the spec to make that legal.  This diff also changes
things to find funclet handler extents using the same logic as the
verifier (relying on funclet bodies being contiguous), since it's
easier to do than forward propagating in RPO until you find an Unwind
now that there can be try/catch blocks inside the funclets.

Reviewed By: @edwinsmith

Differential Revision: D1088288
2013-12-08 10:30:08 -08:00
Jordan DeLong 72a60e57d8 Replace some CHECK/DCHECK macros with {always_,}assert
Facebook: OSS warnings are ok.

Reviewed By: @ptarjan

Differential Revision: D1084382
2013-12-08 10:30:05 -08:00
Jordan DeLong f66acb92f6 Add smart_new and smart_delete
Instead of manually calling placement new or destructors with
smart_malloc and smart_free.  Since these are type-aware, they also
can easily use smartMallocSize/smartFreeSize to make a smaller
allocation.

Reviewed By: @swtaarrs

Differential Revision: D1084270
2013-12-08 10:30:02 -08:00
Jordan DeLong a1c36a0663 Clean up and fix some bugs in setOpProp and incDecProp
These functions were a bit hard to understand, and both
contained a reference leak in cases involving magic getters.  There
were also some behavioral differences from zend with protected
properties that are fixed.  It's very tempting to try to template this
and combine the two functions---they're almost the same, but just
barely not quite, so I'm leaving them separate for now.

Reviewed By: @dariorussi

Differential Revision: D1084236
2013-12-08 10:29:59 -08:00
Jordan DeLong 90302d9b12 Fix a reference leak in setop
I think there are a couple others relating to dynamic
properties and magic methods, but this one is independent enough for
its own diff.

Reviewed By: @swtaarrs

Differential Revision: D1084106
2013-12-08 10:29:56 -08:00
Jordan DeLong ad522a5d12 Allow magic property methods to be entered recursively
Common idioms in php require magic methods to be allowed to
be entered recursively.  This diff makes hhvm mostly match zend on the
behavior here: recursion is allowed until it hits the same magic
method for the same property on the same instance.  For now there are
still some slight divergences in cases where there are also declared
protected properties with the same name (and we'll differ for now in
some cases where zend SEGVs).

There are a few things still here that look like bugs in some object
property reference counting (at least one case with setop of an object
prop seems to leak a reference).  I've tasked them to look at later so
we can get this in, though.  (They aren't all related to magic
methods.)

Reviewed By: @swtaarrs

Differential Revision: D1083309
2013-12-08 10:29:53 -08:00
Jordan DeLong 0aa65af3d7 Improve assertion for pmethodCacheMissPath---update write lease comments
Reviewed By: @bertmaher

Differential Revision: D1083718
2013-12-08 10:29:49 -08:00
Jordan DeLong e380d389b8 Stop dumping HNI extension bytecode in Eval.DumpBytecode=1
This just needs to mask out the low bit the way normal
systemlib works.  If you want to print the extension bytecodes, you
can set Eval.DumpBytecode=3.

Reviewed By: @markw65

Differential Revision: D1087356
2013-12-08 10:29:46 -08:00
Chip Turner 5838ed9cd6 Revert "Switch to the MySQL 5.6 client"
Dragon has encountered an issue with double close()'s, which is
an issue in the underlyng libmysqlclient library.

This reverts commit 9e5a733ca19b8a199eb7742f90e6c80e46860d1d.

Reviewed By: @tudor

Differential Revision: D1087701
2013-12-08 10:29:42 -08:00
Sara Golemon fc37017a7e Allow building ext_zend_compat extensions
By default, zend source compatability remains disabled,
however you can now explicitly request compilation of the
infrastructure and the extensions it supports via:

  cmake -DENABLE_ZEND_COMPAT=ON .

Note that CMake caches -D defines between runs, so a later call
without ENABLE_ZEND_COMPAT will still retain the option enabled.
Either explicitly set it to OFF, or delete CMakeCache.txt if
switching between the two.
2013-12-07 08:43:32 -08:00
Paul Tarjan 57ff7e8300 record filter test with parameterization
This shouldn't require you to be in the root when running.

Reviewed By: aravind

Differential Revision: D1087979
2013-12-06 16:01:24 -08:00
mwilliams 392322f9c0 Fix cpu identification
I broke this when cleaning up some -fstrict-alias warnings.

Reviewed By: @jdelong

Differential Revision: D1087374
2013-12-06 16:01:21 -08:00
Tianjiao Yin 67b1e660db filter_input_array behaves differently from stock php
fix `filter_input_array(INPUT_SERVER, FILTER_UNSAFE_RAW)`

Reviewed By: @ptarjan

Differential Revision: D1081292
2013-12-06 16:01:15 -08:00
Tianjiao Yin 9fa72145f0 Set json_last_error + message from json_encode
Currently json_last_error and json_last_error_msg only return meaningful values after json_decode, which is confusing since the functions are defined and at first seem like they are fully implemented.

Reviewed By: @ptarjan

Differential Revision: D1078012
2013-12-06 16:01:11 -08:00
Paul Tarjan 110f0c8fe7 fix fprintf flakeyness
I love zend

Reviewed By: @alexmalyshev

Differential Revision: D1087430
2013-12-06 13:40:26 -08:00
Paul Tarjan a906928aff Revert "Add support for IsScalar"
This reverts commit 68bef5478c2495c8328b68b94f687edf4e52b9ae.

Reviewed By: aravind

Differential Revision: D1087216
2013-12-06 13:40:20 -08:00
Owen Yamauchi 9b02b7a35d Disable inlining in ARM mode
It's not the ARM part that kills us here, but the interp-everything
part. The inlining code fails in a couple of different ways if the
instruction that pushes the ActRec is interped. We don't really have a
way to cleanly bail out of inlining if we discover that it's impossible
below the IRTranslator level.

Rather than put in a bunch of effort to sort out that situation,
I'm opting to punt until we get proper ARM codegen for FPush* and FCall,
at which point we should be able to turn on inlining without trouble.
I've tasked it so we don't forget.

Reviewed By: @jdelong

Differential Revision: D1085589
2013-12-06 10:15:57 -08:00
Dario Russi e24812581f Adding a possible cache for enum values based on static arrays
When defining an enum it is useful to have the values cached in a static array given Enum don't change value

Reviewed By: @markw65

Differential Revision: D1086167
2013-12-06 10:15:57 -08:00
Joel Marcey ea78e22439 Make the "Run Test File" command better.
Make the "Run Test File" command for tests that don't have an expected status beter for frameworks that don't run in parallel. For those frameworks, the test run command does not contain the individual test. And currently we can't run the individual test that is not behaving as expected without jumping through a few manual hoops. Turns out there is access to the test name while we are running, even serially. Use it.

Reviewed By: @alexmalyshev

Differential Revision: D1085298
2013-12-06 10:15:57 -08:00
Alex Malyshev 82c048f161 Correctly set connection fields in PDOMySqlStatement
PDOStatements have a field for their PDOConnection. Turns out
PDOMySqlStatements have an extra field that stores their
PDOMySqlConnection, which they use instead. Synchronize the two,
as currently it's not possible to run pdo_handle_error without
hitting throw_null_pointer_exception().

Reviewed By: @ptarjan

Differential Revision: D1084318
2013-12-06 10:15:56 -08:00
Owen Yamauchi 6daaa7c767 Stop VIXL from creating this vixl_stats.csv file
This file gets created unconditionally, for stats logging, even if you
don't have logging turned on. This is annoying. I'm removing that code
from the simulator; if you want stats logging, it's easy enough to add
it yourself by creating vixl::Instrument and adding it as a decoder
visitor (like I do with PrintDisassembler in enterTC).

Reviewed By: @swtaarrs

Differential Revision: D1084658
2013-12-06 10:15:56 -08:00
Owen Yamauchi a06c1ac005 Implement reusable service requests for ARM
While doing this, I made CodeCursor not depend on X64Assembler and moved
it into a different file.

Reviewed By: @jdelong

Differential Revision: D1083358
2013-12-06 10:15:56 -08:00
Jordan DeLong ad8dfe4d6d Replace unused ObjectData::HasCallStatic with ObjectData::HasClone, use it
A measurable percentage of L1 dcache misses in production are
coming from lookups of the __clone function in ObjectData::cloneImpl.
If a decent number of them don't have custom __clone functions, we can
just check an o_attributes bit (which we just checked in ::clone, so
it should still be in dcache).  (This diff doesn't avoid the redundant
load of o_attributes, though.)

Reviewed By: @ptarjan

Differential Revision: D1070758
2013-12-06 10:15:55 -08:00
Enis Rifat Sert 0e7c2522af preg_replace error return values
Fixed preg_replace error return values

Reviewed By: @ptarjan

Differential Revision: D1077072
2013-12-06 10:15:55 -08:00
Joel Marcey 6bacabaccf Remove --no-edit from pull requests
--no-edit for pull requests was causing issues on Ubuntu 12.04 running the script.

Error was: error: unknown option `no-edit'

Took it out. Things ran fine. Pull requests still worked for doctrine and pear.

Reviewed By: @alexmalyshev

Differential Revision: D1084828
2013-12-06 10:15:55 -08:00
Joel Marcey 7042330fa0 Create php symlink for OSS
We don't have a php symlink to the hhvm executable in oss land. Create one so Pear can work correctly. Otherwise we will literally have 0% for Pear.

Reviewed By: @ptarjan

Differential Revision: D1084685
2013-12-06 10:15:55 -08:00
Sara Golemon 1d5f027b1f Refactor intl subcomponents into the intl extension
Mostly organizational frufaru
This moves us away from having multiple icu_* extensions
and closer to having a single 'intl' extension
similar to Zend.  icu_ucnv and icu_uspoof will be
folded in when they are converted to HNI.

Future intl classes (DateFormatter) will be added here.

Reviewed By: @ptarjan

Differential Revision: D1083189
2013-12-06 10:15:48 -08:00
Emil Hesslow 6fc1f1eb3f Some changes to Zend test importer
- Make it not fatal if the zend path don't contain a / in the end
- Better error message when using --only and it doesn't match any files

Reviewed By: @ptarjan

Differential Revision: D1083278
2013-12-06 09:14:22 -08:00
Paul Tarjan f34b3e2218 remove __tmp_oo_rename3
this test didn't clean up after itself

Reviewed By: enis

Differential Revision: D1084661
2013-12-06 09:13:31 -08:00
Bert Maher fb151725d2 Improve FPushCuf -> FPushObjMethod transformation
The previous version of this optimization was a bit too picky
about where it found the object input to the FPushCuf.  This fixes it
up so it catches most of the hot cases in www.

Reviewed By: @swtaarrs

Differential Revision: D1054142
2013-12-05 12:03:41 -08:00
Jordan DeLong 881604d2c0 Rename ObjectData::HasClone to HasCppClone
This means the ObjectData has a C++-level clone
implementation.  Also clean up some duplicate specifications of the
template parameters for ExtObjectDataFlags.

Reviewed By: @edwinsmith

Differential Revision: D1070691
2013-12-05 12:03:40 -08:00
bsimmers 7bc30bf3a4 Runtime option to limit the amount of code we translate
This allows us to stop translating gracefully once we've emitted a
certain amount of code to a. I also fixed the names of the RuntimeOption
members to match the config options they map to.

Reviewed By: @ottoni

Differential Revision: D1081564
2013-12-05 12:03:40 -08:00
Paul Tarjan 92346aa00d handle running the script from any dir
I shouldn't require you cd to `hphp`

Reviewed By: @jdelong

Differential Revision: D1083592
2013-12-05 12:03:40 -08:00
Guilherme Ottoni 614a8fed9d Get tests passing again with the region JIT
Some of the work during lockdown exposed a few issues with the region
JIT enabled.  Most of the issues were because jump optimizations was
mutating an instruction into another one with a different number of
dests, including SideExitJCCs and SideExitGuardLoc.  These were fixed
by making these instructions have the similar dests as their
corresponding instructions.  For the JCCs, ideally we should get rid
of their None dests. I tried that, but unfortunately it's not that
simple and will require changes to the simplifier at least.  To
unblock work on the region JIT, I'm taking the simplest approach here
by making SideExitJCCs have a dest too, and I'll task cleaning up the
dests of all these instructions.

Reviewed By: @swtaarrs

Differential Revision: D1082383
2013-12-05 12:03:39 -08:00
Joel Marcey 6d5b5126a0 Fix get runtime executable for oss
The check for the hhvm runtime build in oss land was wrong. This attempts to fix that. Also, we have no "php" symlink to hhvm in oss world, so I removed that check.

Reviewed By: @sgolemon

Differential Revision: D1083192
2013-12-05 12:03:39 -08:00
aravind 0770b4d28d Add support for IsScalar
Add support for IsScalar in IsType instruction.

Reviewed By: @ottoni

Differential Revision: D1045411
2013-12-05 12:03:39 -08:00
Joel Marcey 878ceb348c Update Pear hash
The Pear folks have accepted my pull request. Use the pear git source again. We are actually losing 2.5% on Pear for some reason, but this is happening with the current hash (as shown in our graph) or with this new hash. So that is a wash. Use the newer hash.

Reviewed By: @alexmalyshev

Differential Revision: D1082918
2013-12-05 12:03:38 -08:00
Sara Golemon f240dfe091 Allow loading of named mini-systemlibs
The Intl extension is massive and is best
organized into multiple sub-extensions (icu_ucnv, icu_locale,
icu_num_fmt, icu_date_fmt, etc...).

Extending the loadSystemlib() helper to load from multiple
systemlibs allows us to follow this pattern in the intl module:

  void moduleInit() override {
    BindIntlFuncs();
    loadSystemlib(); // loads intl's main mini-systemlib
    BindLocaleFuncs();
    loadSystemlib('icu_locale');
    BindUCnvFuncs();
    loadSystemlib('icu_ucnv');
    // etc...
  }

Reviewed By: @ptarjan

Differential Revision: D1081324
2013-12-05 12:03:38 -08:00
Sara Golemon 43a407c5c4 Add ICU Locale class
More intl implementations

Reviewed By: @ptarjan

Differential Revision: D1081026
Differential Revision: D1083822
2013-12-05 12:03:38 -08:00
Paul Tarjan a810b449ee re-import php-src tests
Now that lockdown is done we are at 50.77%. This is from the newest 5.5
branch. 18b7875fab791bb88d73df360fd91f1ace70c5b3 to be exact.

The following tests were added to the bad directory. All of them for 2
reasons. Some date format thing changed (years are now 2 digits) and
they now are setting a constant as case-insensitive which we emit a
warning for so it breaks the test.

* test/zend/bad/ext/date/tests/DateTime_format_basic2.php
* test/zend/bad/ext/date/tests/date_constants.php
* test/zend/bad/ext/date/tests/gmdate_variation13.php
* test/zend/bad/ext/standard/tests/file/file_get_contents_basic.php
* test/zend/bad/ext/standard/tests/file/file_get_contents_file_put_contents_basic.php
* test/zend/bad/ext/standard/tests/file/file_get_contents_file_put_contents_variation1.php
* test/zend/bad/ext/standard/tests/file/file_get_contents_file_put_contents_variation2.php

The following tests failed in repo mode, so I made them `.norepo`:

* test/zend/good/Zend/tests/bug47593.php
* test/zend/good/Zend/tests/bug60771.php
* test/zend/good/Zend/tests/error_reporting03.php
* test/zend/good/Zend/tests/error_reporting08.php
* test/zend/good/Zend/tests/halt_compiler2.php
* test/zend/good/ext/exif/tests/bug62523_1.php
* test/zend/good/ext/exif/tests/bug62523_2.php
* test/zend/good/ext/exif/tests/bug62523_3.php
* test/zend/good/ext/exif/tests/exif_encoding_crash.php
* test/zend/good/ext/sqlite3/tests/sqlite3_23_escape_string.php
* test/zend/good/ext/standard/tests/array/sizeof_variation4.php
* test/zend/good/ext/standard/tests/file/bug30362.php
* test/zend/good/ext/standard/tests/file/readfile_variation6.php
* test/zend/good/ext/standard/tests/streams/stream_resolve_include_path.php
* test/zend/good/ext/standard/tests/strings/wordwrap.php
* test/zend/good/ext/standard/tests/url/parse_url_basic_001.php
* test/zend/good/ext/zlib/tests/gzcompress_variation1.php
* test/zend/good/ext/zlib/tests/gzdeflate_basic1.php
* test/zend/good/ext/zlib/tests/gzdeflate_variation1.php
* test/zend/good/ext/zlib/tests/gzencode_variation1-win32.php
* test/zend/good/ext/zlib/tests/gzencode_variation1.php
* test/zend/good/ext/zlib/tests/gzuncompress_basic1.php
* test/zend/good/tests/classes/unset_properties.php
* test/zend/good/tests/lang/include_variation3.php

Reviewed By: @JoelMarcey

Differential Revision: D1081723
2013-12-05 12:03:26 -08:00
seanc f32b9e6b15 Further split Travis test matrix
Summary: Travis tests are still timing out, split them up as much as
possible to see if we can get more reliable results.
2013-12-05 07:42:44 -08:00
Joel Marcey c0199e49a9 Update phpbb3 hash
I hope they accept my pull request, but for now let's just use my repo.

https://github.com/phpbb/phpbb/pull/1908

Reviewed By: @alexmalyshev

Differential Revision: D1081325
2013-12-04 14:30:58 -08:00
Abel Nieto 200d343729 Change the way in which objects are tagged as collections.
With the introduction of FrozenSet in D1060075, we ran out of bits
in o_attributes to represent new collection types.

This diff changes things so that we only store a 1-bit attribute
IsCollection in o_attributes, indicating (suprise suprise) whether
a particular ObjectData  is a collection or not.

If IsCollection is set, then the precise collection type
(which remains an element of Collection::Type) can be found in
o_subclassData.u16.

Reviewed By: @paroski

Differential Revision: D1070558
2013-12-04 14:30:58 -08:00
Owen Yamauchi ddc04e1a84 Add build flag for ARM mode default
Reviewed By: @swtaarrs

Differential Revision: D1081124
2013-12-04 14:30:57 -08:00
Sean Cannella 51a06f9806 $_SESSION should start uninitialized
$_SESSION should start uninitialized on each request

Reviewed By: @swtaarrs

Differential Revision: D1080275
2013-12-04 14:30:57 -08:00
Max Wang c78a16e0c8 Forgot IOP_ARGS in doFPushCuf declaration
Reviewed By: @jano

Differential Revision: D1081437
2013-12-04 14:30:57 -08:00
Abel Nieto f18e7f4b0e Fix bugs in Set::map
There were two problems with Set::map():

  * the return type of the callback was not being checked, so we could
    end up with a Set of a type other than int or string.

  * we also weren't checking for duplicates -- so, for instance, calling
    map with a constant function (constant in the mathematical sense)
    would give us back a set with repeated elements.

Fix the two points above by making Set::map() use the regular add()
operation (which automagically takes care of everything).

Reviewed By: @paroski

Differential Revision: D1069261
2013-12-04 14:30:56 -08:00
Jordan DeLong b63bf51723 Give a better error message when hhas systemlib is broken
Reviewed By: @alexmalyshev

Differential Revision: D1079598
2013-12-04 14:30:56 -08:00
Alan Frindell caf64ec978 Remove extra realloc/NULL termination from LibEventTransport
All callers of getPostData use the size arg correctly.  I tried searching the git history for why this was ever done, and it goes back to before when hphp was moved from svn to git in 2008.

Reviewed By: @markw65

Differential Revision: D1073159
2013-12-04 14:30:56 -08:00
Alex Malyshev 47863c8add Stop invalid Pipe objects from always asserting in dtor
Pipe::closeImpl did not have a good check for whether the pipe needed
closing. Fix that, and add the warning that zend prints on invalid args
to popen()

Closes #1313

Reviewed By: @scannell

Differential Revision: D1079485
2013-12-04 14:30:56 -08:00
Andrei Alexandrescu d9b4ee6947 Fix for code smell reported by Robert Henry
Robert, an old friend, found a bug in our code.

Reviewed By: @markw65

Differential Revision: D1080348
2013-12-04 14:30:55 -08:00
Owen Yamauchi 05cc1a7862 Put HHVM_ARCH in $_ENV, use it to skip strtotime_leak.php
In the interest of maintaining by sanity by getting automated testing
for ARM mode set up ASAP, I'm putting off (and tasking) figuring out
what's going on with strtotime_leak.php in ARM mode. I added something
to $_ENV that allows PHP code to check what arch it's running as, and
we'll skip strtotime_leak.php if we're in ARM mode.

As part of this, I pulled arch() into its own header file to avoid
including translator-inline.h from the files where the env vars are set
up (it didn't seem right).

Reviewed By: @jdelong

Differential Revision: D1080752
2013-12-04 14:30:55 -08:00
Owen Yamauchi 4fd0be47e6 Get ARM mode passing again
quick, slow, and zend/good almost all pass with this diff, after a bunch of
lockdown breakage. I say "almost" because strtotime_leak.php still
fails. I believe that's a consequence of interp'ing everything, although
there may be a real memory leak there. I'll deal with that in an
upcoming diff.

- Since InterpOne has catch traces now, we can't punt on BeginCatch and
  EndCatch anymore. It seems that for the time being, we can skate by
  without actually implementing catch traces, though. The stack is
  always spilled before InterpOne, and because everything is InterpOne'd
  we're not actually holding anything in registers (so we don't need to
  restore them).

- NewStructArray wasn't accounted for in all places in translator.cpp.

- I reduced the amount of work that mixedbag.php does, so that it
  completes in a reasonable amount of time in ARM mode. It's still
  executing all the same code, just fewer times.

Reviewed By: @jdelong

Differential Revision: D1080648
2013-12-04 14:30:55 -08:00
Jordan DeLong 5acc30fd93 Reorder IsTypeL arguments to match other LA,OA pairs
It's arguable that maybe OA,LA would be a nicer order, but
all the other opcodes that have both subops and a LA take them in the
LA,OA order.  (In general, it appears OA always comes last unless
there is an MA, right now.)  Also remove unused isTypePred thing.

Reviewed By: @swtaarrs

Differential Revision: D1079371
2013-12-04 14:30:54 -08:00
Jordan DeLong ecd4a82dd5 Update hhbbc for the IsType subobcode change
Just adds a function mapping from IsTypeOp to the type
opcodes.

Reviewed By: aravind

Differential Revision: D1079276
2013-12-04 14:30:54 -08:00
Jordan DeLong 7e112d6f81 Convert IsTypeOp to an enum class
Also name the types more like other type names (in both
JIT::Type and HHBBC) for macro-friendliness, and remove default cases
from switches so we'll find places that need to be updated when we add
new cases to the enum.

Reviewed By: aravind

Differential Revision: D1079271
2013-12-04 14:30:54 -08:00
Max Wang 1ca0022e67 Use macros in place of explicit iop*() arguments
This allows us to easily (and conditionally) add additional arguments.

Reviewed By: @jano

Differential Revision: D1075399
2013-12-04 14:30:53 -08:00
James Miller c2c98a584c Implement password extension
This uses @ircmaxell's password_compat library to implement the
password extension on top of the underlying crypt functions.

Closes #992
Closes #1303

Reviewed By: @ptarjan

Differential Revision: D1078315

Pulled By: @scannell
2013-12-04 14:30:14 -08:00
Philippe Ajoux 11a48c87a2 Add PageletServerTaskEvent.
Move PageletTransport definition in pagelet-server.h and create PageletServerTaskEvent to be used for integration with Asio.

Reviewed By: @jano

Differential Revision: D1069174
2013-12-04 11:38:25 -08:00
Alex Malyshev 97240eb364 ReflectionParameter works with parameters index instead of name
So it turns out ReflectionParameter::__construct(string, string) can
also be written as ReflectionParameter::__construct(array, string) and
the now supported ReflectionParameter::__construct(array, int).

Reviewed By: @ptarjan

Differential Revision: D1068773
2013-12-04 11:38:14 -08:00
Alex Malyshev 8f2addf3a4 Reimplement str_getcsv in C++
I originally wrote a hacky str_getcsv with that used fgetcsv() + temp
files in PHP to stop fatals in open source land. This fixes the perf
issues with the old implementation by not using files at all.

Closes #1079

Reviewed By: @scannell

Differential Revision: D999569
2013-12-04 11:38:08 -08:00
mwilliams 49c5186e54 Only enable ahot in RepoAuthoritative mode
In sandbox mode, files change, and we could translate
potentially unlimited numbers of functions into ahot.

Reviewed By: @swtaarrs

Differential Revision: D1079214
2013-12-04 11:37:56 -08:00
mwilliams 017aa4d0c5 Fix crash trying to inline after a bad method call
In some cases, we can statically prove that an FCall will
go to a particular method. But that might depend on the fact that
the FPush* would fatal. eg we know that an object is of class Foo,
or is null. The FPushObjMethodD will fatal if its null, so the
FCall is known to call Foo::method (or an override).

But if we try to inline the FCall bad things will happen if the
FPush* was interped. So don't do that.

Reviewed By: @swtaarrs

Differential Revision: D1078789
2013-12-03 09:30:30 -08:00
Sean Cannella f81e40505e Fix OS X segfault on startup
Fix crash due to maybePop() call reading garbage out of the freelist the first time it is accessed.

Closes #1300

Reviewed By: @jdelong

Differential Revision: D1078982
2013-12-03 09:30:26 -08:00
Sean Cannella 37bc5974f7 Fix OSX warning
Fix OSX warning due to mismatched printf type

Reviewed By: @alexmalyshev

Differential Revision: D1078484
2013-12-03 09:30:22 -08:00
Surupa Biswas 1369b333d6 Parse fatal for Interface method bodies
Generate a parse-time fatal for interface methods with method bodies.

Reviewed By: @hermanventer

Differential Revision: D1062389
2013-12-03 09:30:14 -08:00
Drew Paroski 044ff2e0d0 Move Collection interface to the HH namespace
Closes #1003
https://github.com/facebook/hhvm/issues/1003

Reviewed By: anietoro

Differential Revision: D1079642
2013-12-03 09:30:10 -08:00
Guilherme Ottoni ec2813cf50 Move unique stubs to 'a'
Some of these may actually be hot, and they're small enough that
putting them in 'a' shouldn't hurt.

Reviewed By: @jdelong

Differential Revision: D1069482
2013-12-03 09:30:05 -08:00
Drew Paroski 2880070953 Avoid calling smart_malloc() to allocate 0 bytes in Vector
Some of the logic in the Vector implementation was unnecessarily calling
into smart_malloc() to allocate 0 bytes, which is wasteful. This diff fixes
the issue appropriately.

Reviewed By: anietoro

Differential Revision: D1079298
2013-12-03 09:30:01 -08:00
mwilliams 1cc4324ff7 Don't translate idx when JitEnableRenameFunctions is set
Users are supposed to be able to override idx with
their own version - but that doesn't work if we translate it
during bytecode emission.

We don't really have a good way of knowing whether its been
overridden, however, so use JitEnableRenameFunctions as we
have for other, similar cases.

Reviewed By: @dariorussi

Differential Revision: D1078332
2013-12-03 09:29:52 -08:00
Sara Golemon 3d242a6d9d Bump CMake required version to 2.8.7
Mini-systemlib embedding uses string(MD5 ...)
which is only available in CMake 2.8.7 or later.

Closes #1306
2013-12-03 09:28:05 -08:00
Chip Turner f6413a9d4c Switch to the MySQL 5.6 client
Due to the interdependencies between libraries, converting
portions of the codebase to the 5.6 client independently is not an
option.  This diff moves all of fbcode to 5.6 as well as updates the
async_mysql client to the newer, slightly modified async api.

This diff brings with it the new features in the 5.6 client, most
notably ipv6 support.  It also adds ipv6 support to the php mysql
connect api in the form of '[addr]:port' in addition to the previous
'host:port' syntax for ipv4 addresses.

Reviewed By: agallagher

Differential Revision: D1058111
2013-12-02 13:27:17 -08:00
Owen Yamauchi f18a8fac9f Add default arguments to some zip functions
This was causing a hilarious failure mode in debug builds where
unzipping this data would return the compressed data, because the flags
argument was 0x7a7a7a..., meaning the zip library thought the
FL_COMPRESSED flag (meaning return the compressed data) was set.

The problem was only showing up in interp mode, because I guess interp
mode passes arguments to native functions differently such that it was
picking up dead stack cells. Also, the test wasn't catching it because
both calls returned the same incorrect thing. I edited the test to be
more robust (and fix a variable-name type while I'm at it).

Reviewed By: ptarjan

Differential Revision: D1070357
2013-12-02 13:27:17 -08:00
Owen Yamauchi bf1c17d7e2 Fix type logic of VGetL (and VGetN while I'm at it)
VGetL has an effect on the local: it gets boxed. This was causing us
trouble in interp-everything mode when a local got boxed by being passed
by ref to a builtin and then consumed. (The builtin means the tracelet
won't be broken in between.) This was failing an ext_openssl test.

It hurts to be messing with this old code, especially since we've gotten
this far with this bug always present and it hasn't given us any
trouble. When can we kill it?

Reviewed By: @edwinsmith

Differential Revision: D1071404
2013-12-02 13:27:17 -08:00
mwilliams 4de7c49be1 Fix race in pmethodCacheMissPath
pmethodCacheMissPath smashes code under the write lease,
but there's nothing to prevent two threads going through it in
sequence - resulting in a double free of the pdata.

Check to see if the code has already been smashed, and bail out if
it has.

Reviewed By: @edwinsmith

Differential Revision: D1078180
2013-12-02 13:27:17 -08:00
mwilliams b806c0345f optimize fast path to idx() (take 2)
This reverts commit 9ee6e1013b786b280090a052861e708e7c3fe4c0.

I was not having a good day. The crashes were caused by generating
the bytecode with one version of hhvm, and running it with another
(using HHVM_REPO_SCHEMA to shoot myself in the foot), while trying
to debug the asio issue.

Reviewed By: @dariorussi

Differential Revision: D1078072
2013-12-02 13:27:17 -08:00
mwilliams 36a8ca9f7d Revert "Turn off HHIRRefcountOpts by default"
This reverts commit f5f2fc6faa38098ce95dd509f3b33891ed7b4746.

My base rev was broken when I was testing this - there wasn't really
a problem with the RefcoutOpts.

Reviewed By: @edwinsmith

Differential Revision: D1078057
2013-12-02 13:27:17 -08:00
mwilliams c24b5b05d9 Fix crash in WaitHandle::join
It seems that continuations can complete during the "retry"
step, so we should check for that case.

Reviewed By: jan

Differential Revision: D1078010
2013-12-02 13:27:17 -08:00
Edwin Smith 147e1b43a0 Make VarNR become a KindOfStaticString
Reviewed By: mwilliams

Differential Revision: D1077814
2013-12-02 13:27:16 -08:00
mwilliams 783e2b3604 Turn off HHIRRefcountOpts by default
Getting a lot of crashes in production with it
turned on.

Reviewed By: @dariorussi

Differential Revision: D1077935
2013-12-02 13:27:16 -08:00
mwilliams 87d925f0e0 Revert "optimize fast path to idx()"
This reverts commit 7b38c2fbc414274cd22be32548b6cc86cc9d260a.

It crashes a lot in production.

Reviewed By: @dariorussi

Differential Revision: D1077893
2013-12-02 13:27:16 -08:00
mwilliams ca7ddfefe6 Fix memory leak in HPHP::Socket
Socket and SSLSocket are allocated via ::operator new,
so they need to take care of freeing their own memory when they
are swept.

This was showing up as a gradual leak if Socket's were held until
the end of the request.

Reviewed By: @andralex

Differential Revision: D1077472
2013-12-02 13:27:16 -08:00
Edwin Smith 14eb8f7152 Fix one bug, and some formatting, in new APC code
I noticed this while auditing uses of Variant(bool)

Reviewed By: mwilliams

Differential Revision: D1077812
2013-12-02 13:27:16 -08:00
aravind c3985e8354 Use fewer opcodes for Is* instructions
We are running out of opcode space (>256 opcodes).

Reviewed By: @edwinsmith

Differential Revision: D1075626
2013-12-02 13:27:16 -08:00
seanc f9e9b406c0 Add -Wno-deprecated-declarations
Summary: sbrk() has no equivalent how we use it and we use finite() for
parity with the reference implementation so these are not helpful
warnings.

Reviewed By: @sgolemon
2013-12-02 11:15:33 -08:00
Sara Golemon 7cc068e4c8 Don't rewrite license headers in submodules 2013-12-02 10:31:14 -08:00
Drew Paroski aae55a19c1 Update array_filter() to support collections
Updates array_filter() to support collections, and removes the old C++
implementation of array_filter() which is no longer used. This diff also
updates "foreach ($x as $k => $v)" for Set and FrozenSet so that the
current value is assigned into both $k and $v.

Reviewed By: @dariorussi

Differential Revision: D1071459
2013-12-02 10:31:14 -08:00
Julius Kopczewski f8f9284238 Finally statement support for HHVM.
Finally logic is handled by a new component: FinallyRouter.
The approach taken essentially constructs a simple finite
state automaton that decides which action to take next, once
the control reaches the end of a finally block. The
automaton uses an unnamed local variable "state". It also
uses an additional unnamed local to stash result between the
point of actually returning from a function and invoking
return. In order to minimize perf impact, two copies of
finally blocka are in fact emitted. The first copy ends with
a switch statement and is part of the automaton. The second
copy handles exceptional situations exclusively and ends
with Unwind. When multiple nested finallies exist, multiple
copies of a fault funclet corresponding to the inner finally
will be emitted in order to correctly handle chaining.
Exception chaining is handled using an extended set of
members in Fault (m_raiseLevel, m_raiseFrame,
m_raiseNesting). These values are used to decide whether two
exceptions stored on the top of the m_faults stack should be
chained already, or not yet. Additionally, changes have been
made to grammar files and AST in order to give the emitter
more information about the scope of goto labels. This is
used in order to handle goto from try finally block
correctly. No jumps into try finally are allowed, since
reference implementation (Zend) fatals in this case.

Reviewed By: @paroski

Differential Revision: D1058497
2013-12-02 10:31:14 -08:00
Kun Chen 7e6d9aefc3 ReflectionMethod supports getPrototype
ReflectionMethod will support method getPrototype().

**Please note I added an extra field "originalClass" to class ReflectionMethod because the exception message in ReflectionMethod::getPrototype() needs the original class name. (To be compatible with Zend)**

For example:

  class Base { public function test() {} }
  class Child extends Base {}
  $rf=ReflectionMethod('Child', 'test')

Then $rf->class will be "Base" while $rf->originalClass will be "Child".

The implementation for Func* is coming from https://github.com/php/php-src/blob/0d7a6388663b76ebed6585ac92dfca5ef65fa7af/ext/reflection/php_reflection.c (using Func->baseCls). The difference is that we need to deal with interfaces because Func->baseCls didn't consider interfaces.

For builtin classes, because MethodInfo* doesn't contain baseCls information, so we need to implement the logic from scratch.

Reviewed By: @ptarjan

Differential Revision: D1048239
2013-12-02 10:31:14 -08:00
Paul Tarjan f334742e1f actually fix DateTime on travis
sadpanda

https://travis-ci.org/facebook/hhvm/jobs/14586597

Reviewed By: @markw65

Differential Revision: D1076759
2013-12-02 10:31:14 -08:00
Edwin Smith 982408740a Add test case for unset-last-element followed by append
This demonstrates that the 'next-int-key' state of the array
is not modified by unset, even for the last element.
(php 5.3 and 5.5 do the same thing).

Reviewed By: @ptarjan

Differential Revision: D1074810
2013-12-02 10:31:13 -08:00
mwilliams e432eadd42 Fix invalid Func free
Generators that aren't closures still need to subtract
one pointer's worth from the Func* to get the address of the memory
to free.

Reviewed By: @jano

Differential Revision: D1075816
2013-12-02 10:31:13 -08:00
Dario Russi b110ec08fb Shortcircuit the check for an empty ini file and do nothing if empty
when ini file in runtime config is empty we want to do nothing. Literally nothing

Reviewed By: @markw65

Differential Revision: D1075478
2013-12-02 10:31:13 -08:00
Sean Cannella 88df7ab1a4 Merge pull request #1311 from demon/submodule-syntax
Suggest less typing for submodule setup
2013-12-02 10:16:44 -08:00
Sean Cannella ae16505782 Merge pull request #1304 from TsukasaUjiie/master
Fixed path to hhvm in doc makefile
2013-12-02 10:16:20 -08:00
Sean Cannella 4996c55227 Merge pull request #1310 from demon/libzip-ignore
Ignore libzip.dylib from being checked in
2013-12-02 08:12:31 -08:00
Drew Paroski 1a92fed987 Update README.md 2013-11-30 22:45:05 -08:00
Chad Horohoe 2084060478 Suggest less typing for submodule setup 2013-11-27 14:43:26 -08:00
Sara Golemon 44b47c4b43 Don't modify libmagic files 2013-11-26 21:14:20 -08:00
Drew Paroski 0304e80fb0 Update array_map() to support collections
Updates the C++ impl of array_map() to support collections, and updates
array_map.hhas to call the C++ impl when the second parameter is not an
array.

Reviewed By: @dariorussi

Differential Revision: D1071632
2013-11-26 21:14:20 -08:00
Edwin Smith efdfc6183b Fixed the JIT signature for c_StaticExceptionWaitHandle::CreateFromVM
Passing an ObjectData* as TV was working by accident, should be SSA.

Reviewed By: @markw65

Differential Revision: D1074657
2013-11-26 21:14:20 -08:00
Drew Paroski ffca8933eb Unbreak the debug build
Reviewed By: @elgenie

Differential Revision: D1075465
2013-11-26 21:14:19 -08:00
Drew Paroski 59ef8ddd15 Update call_user_func_array() to support collections
Updates call_user_func_array() to support collections for the second
parameter. Also update call_user_method_array(), hphp_create_object(),
hphp_invoke(), and hphp_invoke_method() to support collections.

In the course of implementing this, I fixed a bug with invokeFunc where it
would pass along the arg array to __call() and __callStatic() methods
without checking to make sure the arg array had integers keys 0 thru n-1.

Reviewed By: @dariorussi

Differential Revision: D1071732
2013-11-26 21:14:19 -08:00
Drew Paroski 7a0b149536 Support "C::{<expr>}()" style method calls
PHP 5.4 added support for "C::{<expr>}()" style method calls. This diff
updates HHVM to support them as well.

Closes #1292
https://github.com/facebook/hhvm/issues/1292

Reviewed By: @scannell

Differential Revision: D1071647
2013-11-26 21:14:19 -08:00
Eugene Letuchy f3d90340a4 reflection parity: default constructor with args is exception
conforms to the docs for http://www.php.net/manual/en/reflectionclass.newinstance.php
 as well as Zend

Reviewed By: @alexmalyshev

Differential Revision: D1070609
2013-11-26 21:14:18 -08:00
Joel Marcey 4cb5b74ff5 Refactor the script. Make finding and executing the framework tests better.
This is phase 1 (the biggest) of a refactoring of the test script. I have broken run.php into 3 areas of focus: the original run.php, the test finder, and other utils.

You can now run the script with the --byfile or --bysingletest option. The --byfile options lets you run the tests by test file name. This is faster. The --bysingletest options lets you run the tests by each single individual test of a framework. This is slower, but let's us support a good --filter option down the road.

Reviewed By: @ptarjan

Differential Revision: D1073658
2013-11-26 21:14:18 -08:00
Alan Frindell 5b856eecf8 wait for servers to finish on exit
The Server::stop() API claims to be asynchronous, but bad things happen if Server::stop() does not synchronously stop the VM as LibEventServer does.  Essentially the main thread can exit and leave the VM threads flapping in the breeze.  Call waitForEnd() on the servers before exiting.

Reviewed By: @markw65

Differential Revision: D1056280
2013-11-26 21:14:18 -08:00
Paul Tarjan b3f6b0cf5c don't require the timezone
travis might run on machines all over the world https://travis-ci.org/facebook/hhvm/jobs/14389509

Reviewed By: @JoelMarcey

Differential Revision: D1073832
2013-11-26 21:14:17 -08:00
Herman Venter afbde6181a Provide a way to serialize the compiler's AST in the form of a PHP Code Model.
The AST classes now have an additional visitor that can serialize the AST in the format expected by the unserialize function. The concrete classes to be produced by the unserialize function can be controlled by passing in a prefix argument to the visitor.

Facebook only:

Also added is an extension function fb_serialize_code_model_for(codeobject, prefix) that takes a string as its first argument, prefixes it with "<?php " and then parses it as if it were an eval string and then returns the serialized AST.

Reviewed By: @paroski

Differential Revision: D1027004
2013-11-26 21:14:17 -08:00
Jordan DeLong 9a48ffa372 Mark ZendObjectData as CPPClass, shrink the handle field
Workaround for #3235411.  These changes are needed so we
can shrink ObjectData without crashing entirely.

Reviewed By: @ptarjan

Differential Revision: D1072781
2013-11-26 21:14:17 -08:00
Paul Tarjan 6830d5dce8 update hash
they took my upstreams

Reviewed By: @JoelMarcey

Differential Revision: D1071534
2013-11-26 21:14:17 -08:00
Bert Maher 59b7c54be7 Improve bstrcaseeq
We can make bstrcaseeq a little bit faster by:
- Bailing out early if the pointers are equal
- Using an 8x unrolled case-sensitive comparison (with 8-byte
  compares) to speed the common case where the strings are the same
  including case
- Using the original version of bstrcaseeq to implement bstrcasestr,
  since there the common case is *not* equal strings.

Reviewed By: @jdelong

Differential Revision: D1069607
2013-11-26 21:14:16 -08:00
Dario Russi a9ed2b4abd optimize fast path to idx()
Inline call to idx against arrays with an int or string key into the caller

Reviewed By: @jdelong

Differential Revision: D1043782
2013-11-26 21:14:16 -08:00
Jan Oravec 69600b269e Move virtual barrier from WaitHandle to WaitableWaitHandle
Make WaitHandle, StaticResultWaitHandle and StaticExceptionWaitHandle
non-virtual. Move the virtual barrier to WaitableWaitHandle.

Reviewed By: @jdelong

Differential Revision: D1070819
2013-11-26 21:14:15 -08:00
Edwin Smith 91bc823b83 Use std::string instead of static StringData for array literals
It's a waste of memory to put the serialized array string in
the static string table, because we only need it when loading
or storing units in the HHBC repo.

Reviewed By: @jdelong

Differential Revision: D1070745
2013-11-26 21:14:15 -08:00
Edwin Smith 44c0c1acce Create NewStructArray opcode for array initialization
Many arrays are created with name/value pair syntax, with all
static string names and no repeat keys; aka "struct-like".  This
diff adds a new opcode to support that pattern.

Reviewed By: @jdelong

Differential Revision: D947681
2013-11-26 21:14:15 -08:00
Jan Oravec 5685a2bfdd Native VM support for wrapping exceptions into StaticExceptionWaitHandle
Replace StaticExceptionWaitHandle::create() extension call with AsyncWrapException opcode.

Reviewed By: @jdelong

Differential Revision: D1045649
2013-11-26 21:14:14 -08:00
Jan Oravec 81ee37e99b Native VM support for wrapping results into StaticResultWaitHandle
Do not use emit StaticResultWaitHandle::create() extension call for
every return from eagerly executed async function. Instead, use
AsyncWrapResult opcode that takes care of wrapping the result into
StaticResultWaitHandle object and returning it to the caller.

Reviewed By: @jdelong

Differential Revision: D1045994
2013-11-26 21:14:14 -08:00
Joel Marcey 7e9bceb27f Fix preg_replace /e functionality for $this style calls
preg_replace /e was failing for $this->foo() style replacements. We were returning $this is null. That was wrong.

Reviewed By: @ptarjan

Differential Revision: D1069658
2013-11-26 21:14:14 -08:00
bsimmers 7b40ccec1e Add ahot and aprof sizes to check-health admin command
Facebook: I also cleaned up and compacted the formatting in a couple scripts.

Reviewed By: @jdelong

Differential Revision: D1070834
2013-11-26 21:14:13 -08:00
Paul Tarjan 6039d0fbef make isInstantiable right
@dariorussi brought this up on the other ctor diff. I think it is a big enough change to do on its own.

Reviewed By: @dariorussi

Differential Revision: D1070445
2013-11-26 21:14:13 -08:00
Paul Tarjan 8fd0510528 fix seialization of protected members when there is a __sleep
I don't know why all this code is copy-pasted, but they forgot a case.

Reviewed By: @alexmalyshev

Differential Revision: D1070176
2013-11-26 21:14:13 -08:00
Eugene Letuchy 94dbd3e5bd jit: make obj-to-bool collection conversion check cheaper
@paroski made the change that moved the size of
 collections to a fixed offset, but didn't go further to actually take
 advantage of that with an assembly version of ##isCollection()##.

Reviewed By: @oyamauchi

Differential Revision: D1067752
2013-11-26 21:14:12 -08:00
Jan Oravec 5cd4f28120 Combine CreateAsync + getWaitHandle() into AsyncESuspend
CreateAsync opcode creates a Continuation object that is wrapped into
AsyncFunctionWaitHandle object by ->getWaitHandle() call. Let's merge
these operations into AsyncESuspend that produces
AsyncFunctionWaitHandle and kill Awaitable/getWaitHandle() API from
Continuations.

AsyncFunctionWaitHandle internally still uses Continuations.

Partially based on Mirek Klimos's summer internship work.

Reviewed By: @jdelong

Differential Revision: D1069759
2013-11-26 21:14:12 -08:00
Jan Oravec 0fbd048228 Remove m_origFunc from c_Continuation
m_origFunc is used only to obtain a name of the enclosing function and a
number of original arguments to locate Closure object (which stores
static locals).

If a Func is a generator, allocate extra pointer size to store a pointer
to the original function. Populate this pointer from getGeneratorFunc()
(i.e. when Create{Async,Cont} is interpreted or compiled).

Reviewed By: @jdelong

Differential Revision: D1067622
2013-11-26 21:14:12 -08:00
Sean Cannella 2b7d62d917 Fix ini parsing leak
Right now we don't clean up the YY_BUFFER_STATE created by the Bison parser after we scan a string -- we simply ignore the return of yy_scan_string and it never gets cleaned up (since yy_switch_buffer on a subsequent call won't delete anything.) Fix that.

Closes #733

Reviewed By: @elgenie

Differential Revision: D1069986
2013-11-26 21:14:11 -08:00
Joel Marcey 22722e81ed Don't commit the md5 file to git
Just keep the md5 file local to your machine. No need to gitify it.

Reviewed By: @alexmalyshev

Differential Revision: D1070836
2013-11-26 21:14:11 -08:00
Joel Marcey e23c9609d6 Came to my senses and fixed the composer.json clowntown check
@elgenie made me come to my senses. New check for composer.json changes.

Reviewed By: @alexmalyshev

Differential Revision: D1070788
2013-11-26 21:14:11 -08:00
Jordan DeLong 0cdfbbd340 Flatten APCObject
Put the property vector immediate following APCObject in
memory.

Reviewed By: @edwinsmith

Differential Revision: D1070249
2013-11-26 21:14:10 -08:00
Jordan DeLong 2cd9ea58b5 Reduce string hashes and class lookups in APCObject::getObject
A good chunk of the calls to hash_string_i in production are
coming from looking up classes while converting APCObjects into
ObjectData.  If the Classes are persistent, we can have them already
looked up.  We can also avoid creating an array just to call
o_setArray.

Reviewed By: @dariorussi

Differential Revision: D1067486
2013-11-26 21:14:10 -08:00
Jordan DeLong 9599b72663 Some improvements to the iter_next "cold" path
Most of the time when we go to the cold path, it's because
we're iterating an APCLocalArray.  Add a specialized version for that.
We were also always going to cold by first going to a function that
checked for various collection types (with very big code)---change
this to a quick check at the front of iter_next_cold that then tail
calls to a function that code collection dispatch on the already
loaded type (compiles as a jump table).  We also bailed for releasing
the array which is easy enough to handle.

Reviewed By: @bertmaher

Differential Revision: D1067317
2013-11-26 21:14:10 -08:00
Joel Marcey 6607d6dca4 Make sure our phpunit binary is the one with our hhvm fix + upstream changes to frameworks
Our vendor/bin/phpunit did not contain our PHP_BINARY fix. So I updated composer to get that version, with a hack to make sure that your runs actually get the latest too. I will remove that Hack later and come up with a better way.

Plus I fixed Symfony to support HHVM (PHP_BINARY) too: https://github.com/JoelMarcey/symfony/commit/eba220f998ed994900e0324d1a8dd54b9656ae37

Symfony is above 97% now.

I will upstream that.

The nothing to do errors are gone from yii now, but didn't help the percentage that much. I updated to their latest master hash anyway.

Reviewed By: @alexmalyshev

Differential Revision: D1070555
2013-11-26 21:14:09 -08:00
Jan Oravec ccd469ca37 Move closure check from run time to compile time
When async functions and continuations are used with closures inside
methods, their generator body needs to be cloned into the enclosing
class. This is currently done in run time, but there is nothing
preventing us to do it in compile time, so let's do it.

Reviewed By: @jdelong

Differential Revision: D1067501
2013-11-26 21:14:09 -08:00
Jan Oravec 66b98ad061 Store name of generator body function in the outer Func
Bind inner and outer generator functions, do not pass the name of inner
function thru CreateCont/CreateAsync immediates.

Reviewed By: @jdelong

Differential Revision: D1067483
2013-11-26 21:14:09 -08:00
Julius Kopczewski 96959f0e28 Closing connection on invalid record in FastCGI.
Changed FastCGI behaviour to close the connection when an
invalid record has been received instead of aborting.

Reviewed By: @ptarjan

Differential Revision: D1061545
2013-11-26 21:14:08 -08:00
Paul Tarjan fa4d66125f ReflectionClass->newInstance() should respect privacy
Reviewed By: @alexmalyshev

Differential Revision: D1069688
2013-11-26 21:14:08 -08:00
Paul Tarjan 9181f5fc6a move MW hash back
the newer version is broken somehow and I don't have time to figure out why

Reviewed By: @JoelMarcey

Differential Revision: D1070426
2013-11-26 21:14:08 -08:00
mwilliams 01ff4de5d0 Fix async functions with statics
We were double adding the statics, which resulted in
an assert in dbg builds, and random crashes in release.

Reviewed By: @jdelong

Differential Revision: D1070112
2013-11-26 21:14:07 -08:00
bsimmers c7f62b6076 Add type prediction bytecodes
This diff adds PredictTL and PredictTStk, which are similar to
AssertTL and AssertTStk but for predictions instead of known types. They're
mostly intended for debugging right now, to help reproduce issues that depend
on certain type predictions being present. In the future we could start
emitting them instead of metadata entries.

Reviewed By: @jdelong

Differential Revision: D1069999
2013-11-26 21:14:07 -08:00
Alex Malyshev c9073fd81f Have hphp_get_method_info check superinterfaces of interfaces
If a method doesn't exist in an interface, then we need to check
all interfaces that it inherits from as well.

Reviewed By: @JoelMarcey

Differential Revision: D1068583
2013-11-26 21:14:06 -08:00
Alex Malyshev 7ceb298849 Enable the bzip2 extension
We already had it implemented, but extension_loaded('bz2') would return
false.

Reviewed By: @ptarjan

Differential Revision: D1069567
2013-11-26 21:14:06 -08:00
Sean Cannella 9a9b42e361 Use CPU time instead of wall time for time limit
Zend PHP does not count in sleeping time into scripts time
limit, HHVM does. Change that for parity reasons.

Closes #1279
Closes #1287

Reviewed By: @markw65

Differential Revision: D1066797
2013-11-26 21:14:06 -08:00
Dario Russi 0b04c8ff0f Introducing APCHandle as a replacement of APCVariant (aka SharedVariant)
Every APC object (aka shared object) now has an APCHandle field used by the concurrent storage. No indirection any longer from APCVariant to the object data (string, object, array)

Reviewed By: @jdelong

Differential Revision: D1023419
2013-11-26 21:13:40 -08:00
Paul Tarjan c6d99f1e8e re-use c_DOMNode for xmlNodePtr
This is how zend does it. They shove the container object into the _private part of the dom node and then re-use it. A test in drupal depends on this and it seems correct for the elements to `===` the same if they really have the same underlying node.

Does this introduce a memory leak? I'm not increffing anything so I think the smart pointer wrapping the `ObjectData*` is keeping the `ObjectData*` alive at all times already, this is just a cache of the pointer.

Reviewed By: @markw65

Differential Revision: D1065371

Revert "re-use c_DOMNode for xmlNodePtr"

This reverts the important part of commit 7f8617bd2895e9a802f0efd219390e9b40a8b41d.

I originally thought that the use of `_private` was a problem so I tried using a thread-local map but that didn't do anything.

While I figure out how to do this properly, just revert so our graphs aren't 22%.

Reviewed By: @JoelMarcey

Differential Revision: D1073217
2013-11-26 21:13:27 -08:00
bsimmers 280f307d34 Properly support $this pointers in refcounting opts
The refcounting optimization now understands the flow of values throw
SpillFrames while inlining. This diff is aimed at fixing correctness issues;
there may be more opportunities for optimization we're missing around inlined
calls.

Reviewed By: @ottoni

Differential Revision: D1063557
Differential Revision: D1075908
2013-11-26 21:13:12 -08:00
bsimmers 255b8b4ed6 Clean up inlining frame elision
The code to eliminate unused inline frames was broken for a few
superficial reasons. Once I fixed those, I found and fixed a few larger issues,
mostly having to do with stack offsets for ReDefSP and DecRef (see the code for
details in comments). Unfortunately I'm going to have to check this in disabled
for now since there's at least one crash remaining and I need to move onto
other things for the moment.

check.cpp now enforces that any instruction that can throw must have a catch
block attached, since a number of optimizations rely on that for
correctness. This exposed a number of old issues, the biggest of which was that
LdClsMethodCache and LdClsMethodFCache had a taken label for a slow exit and
can also throw. Since they need a catch trace to be able to throw correctly, I
split them up into smaller instructions to expose more of the control flow at
the IR level.

Reviewed By: @jdelong

Differential Revision: D1060374
2013-11-26 18:33:26 -08:00
Paul Tarjan 947e16cfbb use my MW upstream
They will pull it, just they are slow.

Reviewed By: @JoelMarcey

Differential Revision: D1070132
2013-11-26 18:23:57 -08:00
Eugene Letuchy a759101869 frameworks runner: support notices
... I'd argue that this should be the default
 and tests that depend on not having notices should not work

Reviewed By: @ptarjan

Differential Revision: D1069033
2013-11-26 18:23:52 -08:00
Joel Pobar c57a6a2828 DatePeriod support
Adds most of DatePeriod support for CodeIgniter unit test

Reviewed By: @JoelMarcey

Differential Revision: D1069304
2013-11-26 18:23:47 -08:00
Joel Marcey 01d5384547 Add some includes upstream to phpbb3
Some tests need some additional includes in order to be run as a single test file. Added them. https://github.com/phpbb/phpbb/pull/1888

Reviewed By: @ptarjan

Differential Revision: D1069949
2013-11-26 18:23:42 -08:00
Owen Yamauchi c7d175ec1d Fix ARM exception crash, add --arm option to test/run
The fakeAR thing isn't necessary now that we have a special fixup
implementation for simulator mode. Combined with @markw65' changes to
functionEnterHelper etc., everything's pretty clean, and function
interception works properly (it didn't before lockdown).

Reviewed By: @edwinsmith

Differential Revision: D1069589
2013-11-26 18:23:36 -08:00
Chad Horohoe 965a70f8dd Ignore libzip.dylib from being checked in 2013-11-26 16:17:41 -08:00
Benjamin Roberts 0cf0624bcf Fixed path to hhvm in doc makefile 2013-11-26 16:01:08 +11:00
Joel Marcey 4ef45eb36d Go to the latest github hash for phpbb3 and get the tests to behave
We were failing many tests in phpbb3 because there was globals clowniness when trying to run their tests with filenames. I sent a pull request up to fix that. In the meantime, use my fork.

Reviewed By: @elgenie

Differential Revision: D1069881
2013-11-22 09:49:17 -08:00
Eugene Letuchy b53c43ec9f frameworks: use branch with joomla sort order
... also rerecorded the .expect

Reviewed By: @JoelMarcey

Differential Revision: D1069868
2013-11-22 09:49:13 -08:00
mwilliams bba9d63c4c Don't pass the wrong type to dom error handlers
The error handler takes an arbitrary "context" pointer.
In our handler, if the pointer is not null, we assume its an
xmlParserCtxtPtr, but there were a few places where we passed
in a different type.

Just pass in nullptr instead.

Reviewed By: @edwinsmith

Differential Revision: D1069579
2013-11-22 09:49:09 -08:00
Paul Tarjan 0c165f824d random test runner fixes
stuff i needed while debugging doctrine

Reviewed By: @JoelMarcey

Differential Revision: D1069627
2013-11-22 09:49:05 -08:00
Joel Marcey 536036ee32 Make Zf2 use the latest dev of PHPUnit with our PHP_BINARY fix
To avoid the dreaded "Nothing to do" error, we need PHPUnit to check for our PHP_BINARY env variable. We had that pull requested accepted by PHPUnit. Now the framework vendor dirs need that version. Start with zf2.

Reviewed By: @ptarjan

Differential Revision: D1069559
2013-11-22 09:49:01 -08:00
Owen Yamauchi e4d019d6c4 Fix ARM mode bustage that occurred during lockdown
- At some point, the order of arguments to InterpOne got switched
  around for no apparent reason in the refcount optimization diff.

- My fix to poly-torture.php got accidentally pseudo-reverted, also in
  the refcount optimization diff.

- The type effects of an interped PushL wasn't accounted for properly.

There are still a few more quick tests that crash. Based on their file
names, I think it's all a single root cause. I'll look at those next.

Reviewed By: @jdelong

Differential Revision: D1068766
2013-11-22 09:48:57 -08:00
Paul Tarjan 8d601df707 assetic is being difficult
Something needs to be done but while we bicker just use this

Reviewed By: @JoelMarcey

Differential Revision: D1069051
2013-11-22 09:48:53 -08:00
Paul Tarjan 926f16e6e4 remove 'now' case from test/slow/datetime/compare.php
This is a bit flakey since the 1 second boundary can tick inbetween the `null` and `"now"` case. That isn't even the main point of this test.

Reviewed By: @markw65

Differential Revision: D1069019
2013-11-22 09:48:49 -08:00
mwilliams 236d270b52 Don't let debug_backtrace read a freed ExtraArgs during unwinding
thats it

Reviewed By: @jdelong

Differential Revision: D1068339
2013-11-22 09:48:41 -08:00
Joel Marcey 8505e3f06e stream_resolve_include_path needs to return false on failure, not null
stream_resolve_include_path() was returning null for invalidity instead of false. Make it so.

Reviewed By: @ptarjan

Differential Revision: D1068148
2013-11-22 09:48:37 -08:00
Paul Tarjan 540e98f962 add pull request
Slim isn't being responsive

Reviewed By: @JoelMarcey

Differential Revision: D1068996
2013-11-22 09:48:29 -08:00
Joel Marcey 270761effb Add phpunit config file support to script test command
Add -c support to the test command for running phpunit from our script.

Reviewed By: @ptarjan

Differential Revision: D1068614
2013-11-22 09:48:17 -08:00
Sean Cannella dfab83ed50 Split HHProf into compile plus runtime options
This splits HHProf (heap profiling) into two different knobs --
one is compile time, because of the overhead in the memory-manager smart
malloc functions, and the other is a runtime option that controls actual
tracking of data. This gets us the ability to have no impact when
compiling without the flag and minimal impact (within 1%) of impact when
compiling with the flag but with the runtime option turned off.

Reviewed By: @mikemag

Differential Revision: D1068213
2013-11-22 09:47:49 -08:00
Paul Tarjan 883456c911 warn on null file to fopen
Without this we hapilly put the `cwd` infront and open a directory. mediawiki has a test failing because of it. This felt like the best place to put it.

Reviewed By: @alexmalyshev

Differential Revision: D1067777
2013-11-22 09:47:45 -08:00
Yermo 8763eed645 Allow rewrite rules to apply to files that exist
Adds a CheckExistenceBeforeRewrite option to allow rewrite rules to take effect even on files that exist on the default path. This option is off by default.

Closes #1283
Closes #1286

Reviewed By: @ptarjan

Differential Revision: D1065548

Pulled By: @scannell
2013-11-22 09:47:40 -08:00
bsimmers 7f74da5701 Disable flaky test/zend/good/ext/standard/tests/file/copy_variation16.php
Reviewed By: @jdelong

Differential Revision: D1068500
2013-11-22 09:47:35 -08:00
Joel Marcey b6a51da104 Fix Reflection to support ordering properties like Zend
Zend orders their properties with child first then parent. We were doing the opposite. Fix that by rearranging the array in php land in reflection.php

Reviewed By: @ptarjan

Differential Revision: D1064961
2013-11-22 09:47:31 -08:00
Owen Yamauchi 4934efdba6 String::String(char) = delete; fix exposed lolbugs
While working on something else, I got bitten by this: if you construct
a String from a char, the char gets promoted to int and that constructor
won't do what you want (it stringifies the int).

To my great joy, this exposed some actual latent bugs, so I fixed them.
E.g. the things that thought they were appending a slash were actually
appending the string "47".

Reviewed By: @swtaarrs

Differential Revision: D1067258
2013-11-22 09:47:13 -08:00
Abel Nieto cde444e097 Add magic methods to the collections IDL.
The magic methods for Pair were missing from the IDL, and so were
not visible from PHP-land.

Add them to the IDL.

Reviewed By: @elgenie

Differential Revision: D1066776
2013-11-22 09:47:08 -08:00
Sara Golemon 26476669f5 Ignore test litter 2013-11-22 09:47:00 -08:00
Paul Tarjan 49be3b1277 clownlist some joomla tests
zend won't pass these without some more setup which I can't figure out how to do

Reviewed By: @JoelMarcey

Differential Revision: D1067754
2013-11-21 14:03:00 -08:00
Paul Tarjan a0e0c8e5a5 exclude 'Broken' group for MW
aparantly instead of disabling them they put them in a Broken group
clowntown

Reviewed By: @alexmalyshev

Differential Revision: D1067762
2013-11-21 14:03:00 -08:00
Paul Tarjan e474dd092d clownlist a yii test
this one needs memcache

Reviewed By: @JoelMarcey

Differential Revision: D1067702
2013-11-21 14:03:00 -08:00
Paul Tarjan 08ac3def46 make the test runner print more
this was useful while debugging the compser thing

Reviewed By: @JoelMarcey

Differential Revision: D1067489
2013-11-21 14:03:00 -08:00
Paul Tarjan a481fc7cb6 add zlib_encode and zlib_decode
Composer needs these functions all of a sudden. I couldn't figure out what they should do from the docs, and looking at the code they look to be identical to the gz versions except they don't force Gzip. Our versions of the gz fucntions don't force GZ anyways so I'll just proxy.

Reviewed By: @alexmalyshev

Differential Revision: D1067316
2013-11-21 14:02:59 -08:00
Sara Golemon 7e6176d120 Add ICU NumberFormatter class (and functions)
Implement to match Zend

Reviewed By: @ptarjan

Differential Revision: D1065096
2013-11-21 14:02:59 -08:00
Sean Cannella f93874910f Merge pull request #1288 from bzikarsky/master
Updated configure_ubuntu_12.04.sh to work on a "clean" ubuntu installation
2013-11-21 11:24:07 -08:00
Benjamin Zikarsky a793e9ae7e Update configure_ubuntu_12.04.sh
- `python-software-properties` must be installed before we try to add the `apt-fast` PPA
- Add automatic initialization of git submodules
2013-11-21 20:06:10 +01:00
Sean Cannella 0c4b037096 Fix OS X compilation
Fix compilaton on OS X due to undefined symbols

Reviewed By: @markw65

Differential Revision: D1067049
2013-11-21 10:38:03 -08:00
Paul Tarjan 12390ea61f update yii hash
they took my upstream fix

Reviewed By: @JoelMarcey

Differential Revision: D1067226
2013-11-20 22:07:57 -08:00
Jan Oravec 6a637a7c7a Fix assert in BlockableWaitHandle::blockOn()
A Gen{Array,Map,Vector}WaitHandle from an outer context may be woken up
and may establish a dependency on a WaitableWaitHandle from an inner
context. Fix the assert.

Reviewed By: @swtaarrs

Differential Revision: D1067182
2013-11-20 22:07:56 -08:00
Paul Tarjan 840da6e18f include upstreamed fix to phpmyadmin
3 more %

Reviewed By: @JoelMarcey

Differential Revision: D1066900
2013-11-20 22:07:56 -08:00
Paul Tarjan d05f4f766a remove the __construct from PDOStatement
@alexmalyshev needs this to fix PDOStatement subclassing

Reviewed By: @alexmalyshev

Differential Revision: D1066791
2013-11-20 22:07:56 -08:00
Alex Malyshev 33787f302a Update laravel hash after upstream fix
Another fix for reusing closures got upstreamed.

Reviewed By: @JoelMarcey

Differential Revision: D1065942
2013-11-20 22:07:55 -08:00
Paul Tarjan c23f2197e6 put m_cls on UserFSNode
I collided with @edwinsmith's removal of m_cls. This is better anyways.

Reviewed By: @alexmalyshev

Differential Revision: D1066263
2013-11-20 22:07:55 -08:00
Jan Oravec ffbd125dc3 Move responsibility for context entering to blockOn callers
BlockableWaitHandle::blockOn() may throw when cross-context cycle is
detected while wait handle enters context. Move this responsibility to
the caller:

- AsyncFunctionWaitHandle and SetResultToRefWaitHandle now perform the check before construction
- the cross-context cycle exception is now catchable from async functions

Related cleanups:

- blockOn & co. are now inlined
- enterContext's likely case is now inlined

Future work:

- maintain parent_context_idx <= child_context_idx invariant for all
  children of Gen{Array,Vector,Map}WaitHandles, so that enterContext()
  is not needed when collection wait handles are unblocked; once done,
  enterContext() calls will occur only on user action (construction of
  WaitHandle and await) and the logic could be simplified

Reviewed By: @jdelong

Differential Revision: D1064798
2013-11-20 22:07:55 -08:00
Paul Tarjan bc3a8b55cd add directory support for userland filesystems
Filling out our userland stream wrapper

Reviewed By: @sgolemon

Differential Revision: D1062493
2013-11-20 22:07:54 -08:00
Jordan DeLong 0d3991962e Treadmill the MethodCachePrimeData after its used
Clean up after ourselves.

Reviewed By: @markw65

Differential Revision: D1060870
2013-11-20 22:07:54 -08:00
Jordan DeLong 88af886439 Combine smart_malloc with the 'size-untracked' freelists
I kept these separate when strings were first moved from the
old SmartAllocatorImpl stuff into here because combining them
increased stores too much.  Now that almost all of the heap is going
through the smartMallocSize api, it seems ok to combine them.  Perflab
showed stores very slightly up (red only on a few endpoints), d-TLB
misses possibly slightly down, d-cache misses down, cpu time in the
noise.

Reviewed By: @edwinsmith

Differential Revision: D1062598
2013-11-20 22:07:54 -08:00
Paul Tarjan 2373167ba9 Treat incomplete like skipped
According to http://phpunit.de/manual/3.7/en/incomplete-and-skipped-tests.html incomplete shouldn't be counted as either a pass nor a fail.

Reviewed By: @JoelMarcey

Differential Revision: D1065446
2013-11-20 22:07:54 -08:00
Joel Marcey 9618294f10 Make some Mediawiki tests clowny
Some of the data sets for these tests fail in Zend as well.

We are getting rid of them all since we clown by file, but in this case that is ok, I think.

We move to 99.88%

Reviewed By: @ptarjan

Differential Revision: D1065351
2013-11-20 22:07:53 -08:00
Jordan DeLong 1203a56f1c Fix instanceDtors for ZendObjectData types
Reviewed By: @ptarjan

Differential Revision: D1065079
2013-11-20 22:07:53 -08:00
Edwin Smith e57aaca9d2 Remove dead m_cls field from ResourceData
it's dead

Reviewed By: @jdelong

Differential Revision: D1065596
2013-11-20 22:07:53 -08:00
Paul Tarjan 5e33aff80f add ViewsDataHelperTest.php to clownylist
This fails in zend

Reviewed By: @alexmalyshev

Differential Revision: D1065420
2013-11-20 22:07:52 -08:00
Paul Tarjan 0bbac0b3e7 clownify validate_range_test.php
These tests all fail in zend with the same error `Creating default object from empty value`.

Reviewed By: @alexmalyshev

Differential Revision: D1065442
2013-11-20 22:07:52 -08:00
Abel Nieto 57e1da0952 Add a FrozenSet extension class (but don't make it a collection, yet)
Add a c_FrozenSet class that inherits from BaseSet and exposes an immutable
interface to PHP-land (it implements ConstSet).

We can foreach over it, but literal syntax doesn't work yet, since it's
not a collection (will make it so in another diff).

Reviewed By: @paroski

Differential Revision: D1051520
2013-11-20 22:07:52 -08:00
Paul Tarjan 1c2d9746d7 Make DateTime serializable
In zend `DateTime` can be serialized. I could try to match their format but as long as we are consistent with ourselves I think this is ok.

Putting that attribute check seems pretty hacky but I couldn't think of a better way.

Reviewed By: @mikemag

Differential Revision: D1063231
2013-11-20 22:07:51 -08:00
Joel Marcey 17ef29c212 Clowntown - The script wasn't counting fatals in stats
Sigh. The script was not printing fatals to the stats file and thus they were not being counted in the percentage.

Reviewed By: @ptarjan

Differential Revision: D1065312
2013-11-20 22:07:51 -08:00
Guilherme Ottoni b6db443d73 Profile to detect hot functions
Use the initial profiling, interpreted requests to detect hot
functions.  Marking them as hot hints the JIT to put them in the ahot
TC area.

Reviewed By: @edwinsmith

Differential Revision: D1063581
2013-11-20 22:07:51 -08:00
Paul Tarjan bbe0eb639f set error_reporting to the php-default for framework tests
and while I'm in there actually make the setting work ;)

Reviewed By: @alexmalyshev

Differential Revision: D1064978
2013-11-20 22:07:50 -08:00
Paul Tarjan 0bc8d16905 add back test/slow/config.hdf
My desire to print more warnings was killing our test coverage for some options.

Reviewed By: @markw65

Differential Revision: D1064717
2013-11-20 22:07:50 -08:00
Paul Tarjan 6dfb28d7b4 make DateTime remember the timezone from the constructor
Reviewed By: @alexmalyshev

Differential Revision: D1065084
2013-11-20 22:07:50 -08:00
Jan Oravec 0b0c3b95a4 Move wait handle declarations to individual header files
Split ext_asio.h into multiple header files, one per each WaitHandle
subclass.

Reviewed By: @jdelong

Differential Revision: D1064750
2013-11-20 22:07:50 -08:00
Paul Tarjan 6f87770554 strip user:pass from url before going to curl
It looks like curl is unhappy when passed a user:pass to `curl_setopt(CURL_URL)`. Lets remove it before we get there.

I could have used `parse_url` and then put it back together, but the regex seemed simple enough... (famous last words)...

Reviewed By: @sgolemon

Differential Revision: D1064319
2013-11-20 22:07:49 -08:00
Paul Tarjan 741ad4cd4d Allow stream_context_create to take an array of headers
Reviewed By: @sgolemon

Differential Revision: D1064310
2013-11-20 22:07:49 -08:00
Paul Tarjan 2e83e734e9 set JitEnableRenameFunction for AuthGuardTest.php
This test uses `debug_backtrace()[0]['args']` to get the args, so we need to keep them around. If we set this always it is a 5% perf regression so only doing it specifically for this test.

Reviewed By: @JoelMarcey

Differential Revision: D1064678
2013-11-20 22:07:49 -08:00
Bert Maher f359d60449 Use store immediate for writing Func* to ActRec in SpillFrame
We were moving the immediate to a register and then to
memory; we can save an instruction by storing directly to memory.

Reviewed By: @jdelong

Differential Revision: D1064108
2013-11-20 22:07:48 -08:00
Jordan DeLong 3c777c570c Specialize array iteration in GenArrayWaitHandle::create
Also, only do one pass over the array, instead of two.

Perflab things it cuts on instructions a very tiny bit, and cuts
branch misses (less than a percent.)  This is adding a place that
assumes packed and mixed arrays have the same value layout---do we
think it's worth that?  (We can always rip it out later, and maybe
GenArrayWaitHandle will become less important if people soon use
Map/Vector WaitHandle instead?)

Reviewed By: @jano

Differential Revision: D1061039
2013-11-20 22:07:48 -08:00
Sara Golemon f1e7c82463 Limit mini-systemlib names to 16 characters
Some platforms (MacOS) don't allow section names
longer than 16 characters.  Use "ext." plus the first
twelve hexits of md5($extname) instead.

This diff also adds an objdump wrapper for checking for
and dumping the contents of mini-systemlib sections.

Reviewed By: @scannell

Differential Revision: D1061643
2013-11-20 22:07:48 -08:00
aravind 20c679133f Support pcre-8.32's JIT
8.32 has a JIT for regular expressions.

Reviewed By: @ottoni

Differential Revision: D1052476
Differential Revision: D1067435
2013-11-20 22:07:34 -08:00
Sara Golemon ec1d6c6b26 Make sqlite3 testless flakey
Destructor timing makes this test just everso-slighty
nondeterministic.  (I occaisionally see it kick in between the
last two tests rather than before them).

Move the close to the end and it'll always happen in the right order.

Also change expectf "finalised" to "finali%ced" to
account for libsqlit3's switch from Brittish English to American English.
Or maybe it was the other way around. Either way... Ugh.

Reviewed By: @ptarjan

Differential Revision: D1065633
2013-11-20 14:38:47 -08:00
Jordan DeLong 86224fbae8 Fix a bug in func prologue guards---it used cmpl instead of cmpq
Unlikely case: if we called the wrong Func, the target Func
was in low memory but the actual Func wasn't, and the guard and
actually-called Func have the same low 32-bits, it would pass the
guard.  While here, also change a few assembler calls to use the new
api.

Reviewed By: @edwinsmith

Differential Revision: D1060995
2013-11-20 14:38:47 -08:00
Alex Malyshev 6c1fb74fe8 Implement ReflectionFunctionAbstract::getClosureScopeClass()
Needed for laravel

Reviewed By: @ptarjan

Differential Revision: D1062117
2013-11-20 14:38:46 -08:00
Joel Marcey 8d92efa6a9 Fix Mediawiki Install
Need to call parent::install() first before creating LocalSettings.php

Reviewed By: @alexmalyshev

Differential Revision: D1063867
2013-11-20 14:38:46 -08:00
Jordan DeLong 95975ac58b Remove CSE flag from several Array-related opcodes
We have to know nothing mutated the array on the other side
of the SSATmp representing the array.

Reviewed By: @markw65

Differential Revision: D1060861
2013-11-20 14:38:46 -08:00
Jordan DeLong 55d6180140 Remove CSE flag from LdFuncCachedSafe, and a few others
For LdFuncCachedSafe, if it returns null, we can't cache it
without knowing if something inbetween defined the func.  The other
ones might work but are too dubious for now.

Reviewed By: @edwinsmith

Differential Revision: D1060858
2013-11-20 14:38:46 -08:00
Jordan DeLong 3062a5c1f1 Remove CSE flag on LdClsMethod{F,}Cache
These are essential and need to mutate an actrec.  I'm not
sure why they have CSE.

Reviewed By: @ottoni

Differential Revision: D1060857
2013-11-20 14:38:46 -08:00
aravind ded1d9a1a5 Continuation object changes
1. Restructure c_Continuation to put the Continuation object
after the ActRec.
2. Cache the entry TCA for the continuation function in the
Continuation object.

Reviewed By: @jdelong

Differential Revision: D1055946
2013-11-20 14:38:46 -08:00
Jan Oravec e058bde149 Detect cycles only when necessary
Move the responsibility for cycle detection from blockOn() to its
caller. Do not detect cycles when the parent wait handle is being
creates, as it's impossible for new cycle to be introduced that way.

Also, it was previously not possible to catch a cycle exception by
adding try/catch around the await. Fix it.

Reviewed By: @jdelong

Differential Revision: D1062770
2013-11-20 14:38:46 -08:00
Jan Oravec 0bbdc8af8f Simplify AsyncFunctionWaitHandle, take advantage of eager execution
Eager execution semantics guarantees that "await" can reenter ext_asio
only with blocked WaitableWaitHandle. Also, an AsyncFunctionWaitHandle
is constructed only when blocked WaitableWaitHandle is encountered.

Take advantage of that, kill all dead code and simplify the rest.

Reviewed By: @jdelong

Differential Revision: D1062521
2013-11-20 14:38:46 -08:00
Alex Malyshev 53172b6bc4 Sync VM regs before executing SQL queries
The SQL queries can have UDFs in them, which causes havoc with the JIT
if we haven't sync'd our registers beforehand.

Reviewed By: @jdelong

Differential Revision: D1060223
2013-11-20 14:38:45 -08:00
Alok Menghrajani ed50758e0f Revert "Switch nullable type failures to recoverable_error"
This reverts commit 83c970e1d8c01fd6e20c2cdb32d6a047c79edc4d.

Reverting this will allow us to run old revisions of www in perflab. I can
bring this diff back in a few weeks.

Reviewed By: @jdelong

Differential Revision: D1062203
2013-11-20 14:38:45 -08:00
Sean Cannella 44c3020a7c Replace slice_array(func_get_args, C)) with hphp_func_slice_args(C)
array_slice(func_get_args(), N) ends up making array copies that are unnecessary. Provide a new library function to deal with this pattern.

Reviewed By: @markw65

Differential Revision: D1057678
2013-11-20 14:38:45 -08:00
Fred Emmott 47384d7426 Add support for /etc/hhvm/config.hdf fallback
Add support for reading /etc/hhvm/config.hdf as a fallback if no configuration file is specified on the commandline.

Closes #1251
Closes #1275

Reviewed By: @edwinsmith

Differential Revision: D1061239

Pulled By: @scannell
2013-11-20 14:38:45 -08:00
Bert Maher 787ebdc7b1 Use inline stores for object property initialization
When we know the object properties at jit time we can just
emit stores inline to do initialization, instead of calling memcpy.

Reviewed By: @markw65

Differential Revision: D1063044
2013-11-20 14:38:45 -08:00
Sean Cannella a6638af048 Fix OS X compilation warnings
Fix more printf type compilation warnings

Reviewed By: @markw65

Differential Revision: D1063319
2013-11-20 14:38:45 -08:00
Joel Marcey 7078150b4d Fix Pear some more. We now pass 95%+ of running tests.
Fix Pear to support HHVM error messages. Upstream changes.

https://github.com/pear/pear-core/pull/23

Reviewed By: @ptarjan

Differential Revision: D1063129
2013-11-20 14:38:45 -08:00
Stephen Heise 06fdff0f29 Include kernel instructions in perf counts
This patch standardizes that we always collect user+sys stats,
not just user stats.

Having fewer counter flavors is a prerequisite for one-day
sharing counters in the kernel.

Short-term this patch will change perflab behavior to start to count
kernel instructions.

Other tools such as perf and dynolog already collect user+sys stats.

Reviewed By: @markw65

Differential Revision: D1059681
2013-11-20 14:38:45 -08:00
Yumikiyo Osanai a2137e9825 Fix error_get_last() to be compatible with Zend
Make BaseExecutionContext::recordLastError() virtual since
file/line number information is only accessible in VMExecutionContext.

Closes #1260
Closes #1281

Reviewed By: @alexmalyshev

Differential Revision: D1061728

Pulled By: @scannell
2013-11-20 14:38:44 -08:00
Guilherme Ottoni 519d0e92ed Update support for perf events
The support for LLC and dTLB more precise events don't work in perf
anymore, so update them to use the more generic (but less accurate)
events.  While here, I added support for more events in tc-print:
iTLB, L1I, and L1D misses.

Ths diff also fixes a couple of issues in Func to deal with the fact
that a tx64 object is not created in tc-print anymore. These issues
were introduced when we got rid of Translator::Get() and company
recently, and they were seg-faulting tc-print.

Reviewed By: @bertmaher

Differential Revision: D1062649
2013-11-20 14:38:44 -08:00
Paul Tarjan 73bb00ac49 Make PDOStatement::__construct callable
zend can call it and a laravel unit test does

Reviewed By: @alexmalyshev

Differential Revision: D1062725
2013-11-20 14:38:44 -08:00
Owen Yamauchi b85fa7d06f Kill ATTRIBUTE_COLD
With our new linker script technology, we don't need this anymore.

Reviewed By: @edwinsmith

Differential Revision: D1062500
2013-11-20 14:38:44 -08:00
Sara Golemon 4a23fdc0dc Provide blowfish implementation for crypt()
Mostly an import of Zend code.

Reviewed By: @ptarjan

Differential Revision: D983797
2013-11-20 14:38:44 -08:00
Joel Marcey 6ff5f5ec7b Fix the way we find test files...
Instead of some sort of brute force, best effort way to get the test files, use the phpunit xml provided by each framework (if there is one).

Record the expect files again with this new information.

(Also, fixed a minor bug where Incomplete tests were not being put in the errors file)

Reviewed By: @alexmalyshev

Differential Revision: D1062413
2013-11-20 14:38:44 -08:00
Joel Marcey 21800bf32a Fix ZipFile. It was breaking Pear tests. And it wasn't matching Zend either.
Our ZipFile implementation was not matching Zend, particuarly in tell() and seek(). This reared its ugly head with the Pear test suite. So, I tried to fix this, using PlainFile as a model.

Reviewed By: @ptarjan

Differential Revision: D1061351
2013-11-20 14:38:43 -08:00
Abel Nieto 42b20b441a Abstract the functionality in c_Set into a base class.
As a first step in implementing FrozenSet, move *all* the functionality in
c_Set to an abstract BaseSet class. c_Set and c_FrozenSet can then both
inherit from BaseSet, except that they expose different PHP "interfaces"
(i.e. FrozenSet doesn't have any of the mutable methods).

Reviewed By: @paroski

Differential Revision: D1050796
2013-11-20 14:38:43 -08:00
Jordan DeLong 8c64de9a8c Replace a few instanceof(c_WaitHandle::classof()) checks with object attr
Now that we have it, might as well use it.

Reviewed By: @jano

Differential Revision: D1061030
2013-11-20 14:38:43 -08:00
Jordan DeLong d04d42f67a Prime method cache across requests by smashing an immediate in the TC
Reviewed By: @bertmaher

Differential Revision: D1060868
2013-11-20 14:38:43 -08:00
bsimmers 68d745477c Disable flaky Zend test
Reviewed By: @dariorussi

Differential Revision: D1061932
2013-11-20 14:38:43 -08:00
Alex Malyshev e7f2916b30 Have Reflection track the use variables of a closure
Need their name and value for ReflectionFunction::getStaticVariables

Reviewed By: @ptarjan

Differential Revision: D1060435
2013-11-20 14:38:43 -08:00
mwilliams 5017e3c6cc Use huge pages for the hot part of the runtime
MADV_HUGEPAGE only works on anonymous, privately mapped
memory. So re-map the hot part of the binary, and mark it huge.

Reviewed By: @edwinsmith

Differential Revision: D1061057
2013-11-20 14:38:43 -08:00
Sean Cannella db03be5f53 Fix clang errors
Fixing some clang errors that look like real bugs.

Reviewed By: @edwinsmith

Differential Revision: D1061452
2013-11-20 14:38:43 -08:00
Paul Tarjan 8d83afeaee Fill out user-land stream wrapper
This was a little broken. It is still a bit different from zend, but at least VFS works.

Reviewed By: @sgolemon

Differential Revision: D1053993
2013-11-20 14:38:42 -08:00
Julius Kopczewski 20dc3d7630 Fixing FastCGI support for KEEP_CONN
Fixing support for KEEP_CONN = false. The connection is now
closed *after* the currently server request is responded to.

Reviewed By: @scannell

Differential Revision: D1057616
2013-11-20 14:38:42 -08:00
Paul Tarjan 72286be212 fix ReflectionProperty for dynamic classes
I fixed ReflectionClass before, this should use it

Reviewed By: @dariorussi

Differential Revision: D1061173
2013-11-20 14:38:42 -08:00
Paul Tarjan 8a2f760ea1 update CodeIgniter Hash
They fixed the preg yelling upstream

Reviewed By: @JoelMarcey

Differential Revision: D1061177
2013-11-20 14:38:42 -08:00
Alex Malyshev dc3303356c Make ini_get('allow_url_fopen') return true
Needed for Assetic

Reviewed By: @ptarjan

Differential Revision: D1060610
2013-11-20 14:38:42 -08:00
seanc 874c9049e0 Add GCC 4.7.x workaround for asio
Summary: asio needs _GLIBCXX_USE_NANOSLEEP to compile on 4.7.x as well.
2013-11-20 07:25:03 -08:00
Paul Tarjan d71b06ace3 Don't email anyone since we do bulk pushes
The person who's diff is on top is not necessarily to blame
2013-11-19 18:14:34 -08:00
Jordan DeLong 5dfe3fec2e Add AsyncAwait opcode to speed up await code path
The logic for await expr is:

  - check if expr is null, if so return null
  - if expr is not a WaitHandle, call getWaitHandle

  - if the wait handle is finished, either pull out its result or
    throw its exception
  - else if it's unfinished, either suspend the continuation or if
    we're eagerly executing the async function, wrap it in a result
    wait handle and create an async function that will continue here.

This diff changes the null check to not do reference counting (use an
unnamed local instead of Dup), and makes an opcode to speed up the
logic in the second part, by removing function calls and reference
counting due to another Dup.

Reviewed By: @jano

Differential Revision: D1058415
2013-11-19 13:40:42 -08:00
bsimmers d15d5e045b New refcount optimization pass
This diff replaces the old DCE-based refcount optimization with one
based on an algorithm we trust a lot more. Both optimizations rely on each
produced reference being consumed exactly once, and this new pass verifies that
fact as it goes along. This caught a number of leaks and other refcounting bugs.

I tried to heavily document the code itself, so for an overview of the
optimization start at the optimizeRefcounts function in refcount-opts.cpp. A
few notes about changes not contained to refcount-opts.cpp:

- IncRef no longer produces a new SSATmp. This allows us to generate IR in more
  straightforward ways without worrying about which IncRefs chain to which
  DecRefs.
- All refcounting instructions are now marked Essential. DCE will leave them
  alone, and only optimizeRefcounts will move or remove them.
- The code in FrameState that knows how each opcode affects the current locals
  has been separated from the code to update the tracked state of those
  locals. This allows the optimization to also take advantage of this
  knowledge.
- OverrideLoc and SmashLocals have been removed, and their behavior has been
  folded into the instructions they used to follow. This was needed so we can
  process each instruction and its effects on locals atomically.

Reviewed By: @ottoni

Differential Revision: D1044602
Differential Revision: D1062844
Differential Revision: D1054603
2013-11-19 10:38:57 -08:00
Sean Cannella eb8dcf0a91 Fix RecursiveIteratorIterator issues
Fix a couple of issues with RecursiveIteratorIterator

Reviewed By: @aryx

Differential Revision: D1060266
2013-11-18 11:27:37 -08:00
Jordan DeLong 483f0abfb1 Remove CSE flag from GetCtxFwdCall
If this gets CSE'd, we will try to replace it with an IncRef,
which is a type error because it's not a subtype of Gen.

Reviewed By: @edwinsmith

Differential Revision: D1060856
2013-11-18 11:27:36 -08:00
Owen Yamauchi 00c678e8f9 Hoist the first-byte check out of is_strictly_integer
It turns out that checking the first byte of a string to see if it's in
the range ['0', '9'] is a better early-exit than the isStatic + hash
sign bit check. We can also use the NUL-termination invariant to make
the check slightly more efficient: no need to check the length
separately, but just subtract '0' and use unsigned comparison with 9.

Ad hoc instrumentation with stats counters shows that the first-byte
check bails us out in the vast majority of cases.

Reviewed By: @edwinsmith

Differential Revision: D1060828
2013-11-18 11:27:36 -08:00
Jordan DeLong bab354960b Remove HphpArray::m_hash; compute it from the this pointer
Now that @edwinsmith has hoisted various redundant computations of
m_hash, this is adds less instructions.  It's still a slight increase
in instructions, but stores are slightly down and loads in the noise.
It seems better in principle to do some extra math rather than some
extra memory accesses, and it saves a small amount of memory.

Reviewed By: @edwinsmith

Differential Revision: D1060836
2013-11-18 11:27:36 -08:00
Edwin Smith 104556b5b4 Unpeel the loops in HphpArray::find() and findForInsert()
This reduces loads and stores but costs a few more ALU instructions
that initialize registers that don't get used when we only probe
one time.

Reviewed By: @jdelong

Differential Revision: D1053987
2013-11-18 09:17:57 -08:00
Joel Marcey 2161e54895 Update Assetic hash because they fixed a bug
Assetic fixed a bug that was causing test failures for us.

https://github.com/kriswallsmith/assetic/pull/520

Reviewed By: @alexmalyshev

Differential Revision: D1060621
2013-11-18 09:17:53 -08:00
Edwin Smith b1951a2618 Use more ArrayInit
I noticed some unnecessary Array growing when looking at LLC-store-misses,
this fixes a few of the top ones.

Reviewed By: @markw65

Differential Revision: D1057028
2013-11-18 09:17:48 -08:00
Owen Yamauchi d22918b2cb Clean up Translator::Get() and stuff, remove TC-cycling logic
Calling through tx(), TranslatorX64::Get(), and Translator::Get() is
utter nonsense. The global tx64 object now doesn't need to be
thread-local; it can just be global, since there really is only ever one
during the entire process lifetime.

The TC-cycling logic isn't used, hasn't been tested in ages, and as such
is likely broken, so I'm removing it.

I also devirtualized a bunch of crap in Translator, and added the
override virt-specifier to the two legit overrides in TranslatorX64.

Reviewed By: @jdelong

Differential Revision: D1059757
2013-11-18 09:17:44 -08:00
Kun Chen 47a18001b6 Support getShortName and getNamespaceName for ReflectionFunctionAbstract
This diff added two methods getShortName and getNamespaceName to class ReflectionFunctionAbstract,
 so classes ReflectionMethod and ReflectionFunction can use these two methods.

The implementation is compatible with Zend implementation:

https://github.com/php/php-src/blob/0d7a6388663b76ebed6585ac92dfca5ef65fa7af/ext/reflection/php_reflection.c

Reviewed By: ptarjan

Differential Revision: D1058177
2013-11-18 09:17:39 -08:00
Sean Cannella da472bbb4d Remove dead code in hphp/compiler
While working on something else I noticed a bunch of dead code (presumably related to hphpc) so remove it.

Reviewed By: @markw65

Differential Revision: D1059801
2013-11-18 09:17:35 -08:00
Alex Malyshev 6c63687b65 Implement PDO::sqliteCreateFunction (again)
Need to sync VM state before calling functions that execute
SQL queries, some of which are PDOStatement::{execute,fetch}.

Reviewed By: ptarjan

Differential Revision: D1059768
2013-11-18 09:17:26 -08:00
Paul Tarjan 3a9c18fe82 deal with case-insensitivity in get_class_methods
Reviewed By: @jdelong

Differential Revision: D1057571
2013-11-18 09:17:21 -08:00
Joel Marcey 50e24864bc Record the Laravel expect file again after git hash change
We changed the Laravel git has (due to ptarjan getting a pull request accepted). Let's record the expect file again.

Reviewed By: @alexmalyshev

Differential Revision: D1059633
2013-11-18 09:17:17 -08:00
Alex Malyshev 12d4f1a0e6 Add support for named subpatterns in preg_replace*
It was implemented for preg_match but not others.

Reviewed By: ptarjan

Differential Revision: D1052338
2013-11-18 09:17:12 -08:00
Alex Malyshev e1177bf11f Handle UTF-8 chars in string_html_encode like Zend
Changes string_html_decode's behavior with non-ASCII UTF-8 chars to
be more like Zend's.

Reviewed By: ptarjan

Differential Revision: D1055317
2013-11-18 09:17:07 -08:00
bsimmers c26c90206b Disable flaky test/zend/good/ext/standard/tests/file/fileowner_basic.php
Reviewed By: @dariorussi

Differential Revision: D1059751
2013-11-18 09:17:01 -08:00
Joel Marcey 7881fcf3e3 Graylist some tests for Pear and modify blacklist and graylist handling
The Pear tests may be somewhat out of date. There are many tests that fail with HHVM, but also fail PHP 5.5. And, HHVM and PHP 5.5. are printing the same "different than expected" output.

Let's whitelist these tests and don't count them as failures or passes.

During this process, I modified the way we handle blacklist and graylist tests. Basically just move these to "disabled" during the install process. That way we know they won't get executed.

Reviewed By: @ptarjan

Differential Revision: D1058987
2013-11-15 15:04:10 -08:00
Paul Tarjan df859438ee update laravel hash
They took 2 of my fixes upstream.

Reviewed By: @JoelMarcey

Differential Revision: D1058397
2013-11-15 15:04:10 -08:00
Abel Nieto 7372fa38b7 Implement COW when materializing a FV
Invoking a Vector's toFrozenVector() method is now an O(1) operation.

Subsequent modifications to the vector trigger a copy-on-write.

Reviewed By: @paroski

Differential Revision: D1012992
2013-11-15 15:04:10 -08:00
Joel Marcey e1314ffc61 Fix wordwrap. It wasn't matching Zend.
Zf2 tests were failing wordwrap with input like:

wordwrap('foobar*foobar', 6, '*', true);

HHVM would print: foobar**foobar
Zend would print: foobar*foobar

Reimplement wordwrap in PHP-land

Reviewed By: @ptarjan

Differential Revision: D1047300
2013-11-15 15:04:09 -08:00
Alok Menghrajani c14d9fce0b Switch nullable type failures to recoverable_error
The code in www is basically clean with a few last diffs going in
next week. There's no longer any reason to treat these failures in a
different way.

Reviewed By: @paroski

Differential Revision: D1050132
2013-11-15 15:04:09 -08:00
Joel Marcey 7d8e60cc0c Need to check for added pull requests to force possible redownload.
Since we added new pull requests, we need to force a framework redownload if they don't have it. E.g., @ptarjan's cron job needs to redownload Pear because of this.

Reviewed By: @alexmalyshev

Differential Revision: D1057685
2013-11-15 15:04:09 -08:00
Mike Magruder f272385380 Lookup Continuation functions during process init instead of on each next/send/raise call
We were seeing a surprising number of hits with perf in FixedStringMap::find() under WaitHandle::join(). This is used while looking up the methods send, next, and raise on Continuation in c_Continuation:call_send() and friends. Since there's a single method to find, go find it during process init and use the result there instead of doing a string lookup on each call.

Reviewed By: @markw65

Differential Revision: D1056356
2013-11-15 15:04:08 -08:00
Paul Tarjan 8fd0426b88 fix SimpleXML count
It looks like if you have two children with the same name, we just make an array of them. So we have to count them up too.

Reviewed By: @JoelMarcey

Differential Revision: D1054872
2013-11-15 15:04:08 -08:00
Paul Tarjan f8c949707b Fix reflection about private variables in traits
I don't know why they originally did it like this. I think it was just an oversight by Parker last year in D599728

Reviewed By: @JoelMarcey

Differential Revision: D1056703
2013-11-15 15:04:08 -08:00
Paul Tarjan 4a0f934975 Add pretty printer for Class*
Reviewed By: @markw65

Differential Revision: D1056709
2013-11-15 15:04:08 -08:00
Paul Tarjan 525d97518e do special comparisons for DateTime
Zend does, them. We should too. I basically copied `ArrayObject`.

Reviewed By: @jdelong

Differential Revision: D1054508
2013-11-15 15:04:07 -08:00
Paul Tarjan 067577e5c8 make offsetExists match offsetGet
and while I'm there, make it more explicit what the failure case is for offsetGet

Reviewed By: @JoelMarcey

Differential Revision: D1054887
2013-11-15 15:04:07 -08:00
Joel Marcey 5e39267ee6 Pull more code in for PEAR
The file not found errors we were getting for PEAR was due to the fact that we needed more PEAR packages. I added some more pull requests.

Reviewed By: @ptarjan

Differential Revision: D1057255
2013-11-15 15:04:07 -08:00
Edwin Smith 6f3f58a7fa Fix copyPackedAndResizeIfNeededSlow() when only hashtable is full
If m_used==0 but isFull()==true, the hashtable is full but the
array is empty.  We try to copy 0 elements, which crashes because
wordcpy() is a do-while loop.  But also, we should be compacting
in this case instead of growing.  Add an assert, and do compaction.

Reviewed By: @markw65

Differential Revision: D1057100
Differential Revision: D1059120
2013-11-15 15:04:06 -08:00
Joel Marcey 954bbd1cc1 Record the yii expect file again
After @ptarjan's awesome find about the wrong phpunit.xml being used in testing, let's record the yii expect file again.

Reviewed By: @ptarjan

Differential Revision: D1057061
2013-11-15 15:04:06 -08:00
Paul Tarjan 279b14c3bf fix test path for yii
yii has multiple xml files (for example blogs and such) some of which appear alphabetically before `tests`. Lets make sure we find the right one.

Reviewed By: @JoelMarcey

Differential Revision: D1056958
2013-11-15 15:04:06 -08:00
mwilliams c457a79885 Apply some strict-alias warning fixes
Its a little alarming that gcc warns about eg using an
int, and also memcpy'ing to/from that int (which is explicitly
allowed by the standard's aliasing rules).

Reviewed By: @jdelong

Differential Revision: D1052741
2013-11-15 15:03:27 -08:00
Yumikiyo Osanai 3a6a8f282e eval() should return false on syntax errors
eval() should return false on syntax errors

Closes #1267
Closes #1270

Reviewed By: @alexmalyshev

Differential Revision: D1055028

Pulled By: @scannell
2013-11-15 10:13:48 -08:00
Guilherme Ottoni 1211c032db Avoid ret branch miss in Continuation::send, next, raise
These functions are generally called from enterTCHelper, but their
return address is set so that they return to the callToExit stub.
This was causing the ret instruction ending this translations to miss
all the time, since the return address didn't match what the hardware
return address stack predicted.

This diff marks these functions as AttrVMEntry, a new attribute
meaning that the function is generally a VM entry point.  This
information is used to generate a predictable direct branch to the
callToExit stub.

Reviewed By: @swtaarrs

Differential Revision: D1054750
2013-11-15 10:13:48 -08:00
Paul Tarjan 10305b01e9 unwrap all IteratorAggregates in IteratorIterator
Reviewed By: @alexmalyshev

Differential Revision: D1055581
2013-11-15 10:13:47 -08:00
Paul Tarjan 4cd76aae2a implement fileinfo
A direct port of zend's forked libmagic code embeded in the same way they do it. All the bad tests are from `var_dump` imcompatability or unrelated unimplemented functions.

Reviewed By: @paroski

Differential Revision: D1050594
2013-11-15 10:13:41 -08:00
mwilliams a0e1b2409a Don't dump bytecode by default
There also doesn't seem to be a good reason for
forcing the jit off. I'm assuming these got committed by
accident.

Reviewed By: @edwinsmith

Differential Revision: D1055752
2013-11-15 07:51:53 -08:00
Abel Nieto 36bff65cf6 Add test case for mutating collections while iterating
In a previous version of D1012992 I broke Vector by
accidentally disallowing the following pattern

  $v = Vector {1, 2, 3};
  foreach ($v as $e) {
    $v[0] = 42;
  }

i.e. we should be able to mutate elements of Vector (and Map, and StableMap)
while iterating over the collection at the same time.

The bug was caught by a flib unit test, but it seems there wasn't an
hphp unit test that tested the behaviour.

So I'm adding it.

Reviewed By: @paroski

Differential Revision: D1056037
2013-11-15 07:51:42 -08:00
bsimmers a2b39089dd Disable test/zend/good/ext/pcntl/tests/pcntl_wait.php
It's failing in asan builds. Disabling so we can investigate without
time pressure.

Reviewed By: @ptarjan

Differential Revision: D1055854
2013-11-15 07:51:37 -08:00
Paul Tarjan 7cbeaf5a53 make default message work
implode doesn't know what to do with Vectors. I also like having them on their own line for easy copy-paste (I'm ok to undo that if you have a reason not to).

Reviewed By: @JoelMarcey

Differential Revision: D1055626
2013-11-15 07:51:32 -08:00
Joel Marcey d16010495c Add no proxy information for FB internal access (FacebookPHPSDK)
The FacebookPHPSDK curl test was failing since we had a proxy set and that is not good for internal curl access. Add no_proxy settings.

Reviewed By: @alexmalyshev

Differential Revision: D1055647
2013-11-15 07:51:27 -08:00
Enis Rifat Sert a5f9d518e0 Implement ZipArchive
This diff implements ZipArchive class and zip functions of
PHP, as described in http://php.net/manual/en/class.ziparchive.php and
http://www.php.net/manual/en/ref.zip.php respectively.

This diff is not complete, summary and test plan will be updated as
the code revised.  Also I should land a third-party repo commit as
well, libzip, before I land this code.

Reviewed By: @ptarjan

Differential Revision: D1040058
2013-11-14 15:30:58 -08:00
Sara Golemon 8db131ac79 Embed per-extension systemlibs 2013-11-14 14:19:35 -08:00
Joel Marcey dd68b94be2 Bump Twig Hash to add large int parsing fix
@ptarjan successfully got an upstream Twig pull request accepted for tests that parse large ints.

We are now Twig=100% :)

Reviewed By: @alexmalyshev

Differential Revision: D1055267
2013-11-13 19:40:47 -08:00
Paul Tarjan c18087a601 Fix bug causing Pear to fatal
Framework::$parallel needs to be set in the constructor only, or Pear fatals

Reviewed By: @JoelMarcey

Differential Revision: D1054784
Differential Revision: D1054961
Differential Revision: D1055096
2013-11-13 19:40:46 -08:00
Eugene Letuchy 9295135383 collections cleanup: throw_expected_array{_or_collection}_exception
Some array_* utils were migrated to understand collections,
 but still warn that "array_xyz expects array(s)" when passed a
 scalar.  This diff audits all instances of throw_bad_array_exception
 and renames some to throw_expected_array_exception and others to
 throw_expected_array_or_collection_exception, depending on whether
 the function has been migrated.

Reviewed By: anietoro

Differential Revision: D1053736
2013-11-13 14:10:37 -08:00
Joel Marcey 94eed3a392 Fix the flakiness of Pear
WTF PEAR!!?!?!

Well, Pear was out of control running tests in separate process with wildly changing statuseses for a given test depending on the time of day and alignment of the moon. So created a serial option...

We have consistency now. --record and subsequent runs give the same results.

In the future, maybe allow the parallel/serial flag to be set at the command line, but for now just setting this within the framework class itself.

Pear runs much slower this way. Results can't be viewed piecemail (gotta wait until the end of the run). And I will need to fix the test run messages that get printed in the diff/errors/fatals file to extract single test files this way (the message now tells you to run the entire test suite again).

This script is not affecting flib tests.

Reviewed By: @ptarjan

Differential Revision: D1054205
2013-11-13 14:10:36 -08:00
Owen Yamauchi 2eae7c350d Replace REQ_INTERPRET with judicious interp-ones
REQ_INTERPRET is kind of heavyweight when we really just want a
conditional interp-one. This diff replaces REQ_INTERPRET in failure
cases with an interp-one on an exit trace, and removes the ReqInterpret
instruction. We still need the service requests, for the debugger case.

Reviewed By: @swtaarrs

Differential Revision: D1052990
2013-11-13 14:10:36 -08:00
Alex Malyshev 4a03d98ba9 Move string out of bounds warning under HH syntax
Zend doesn't raise a warning, and this causes Joomla tests to fail

Reviewed By: @ptarjan

Differential Revision: D1051636
2013-11-13 14:10:36 -08:00
Jordan DeLong c8f0886f72 Tweak magic call prologues to be a bit more efficient
They were doing increfs and decrefs while trying to get the
args into the packed array, and went through a C++ helper.  They also
would jump backward in the nPassed = 2 case and do a BIND_JMP in the
middle of the prologue, which prevents fallthrough from ever working.
This fixes that, uses the empty array for nPassed = 0, and
disentangles the code from the other prologues.  (I didn't do the same
for the ARM version for now.)

Reviewed By: @markw65

Differential Revision: D1049527
2013-11-13 14:10:35 -08:00
Alex Malyshev 516207b436 Define ENT_SUBSTITUTE, fix flags handling in f_html* functions
We were just casting the flags argument from an int to a
StringUtil::QuoteStyle, but the arg can have more bits set in it.

Reviewed By: @ptarjan

Differential Revision: D1053206
2013-11-13 14:10:35 -08:00
Joel Marcey 0e404be0b6 Print better test run information.
Print out the actual command line string to run a given test. This will be printed in the errors/fatals/diff files.

Reviewed By: @ptarjan

Differential Revision: D1053801
2013-11-13 14:10:35 -08:00
Joel Marcey b84d93eb4a Fix install bug after move to Framework classes
This bug basically prohibited the install of frameworks. Why? Because I was doing setXXX calls in the Framework constructor even if the framework wasn't installed. So I fixed that. To do this quickly, I removed the parallelization of multiple framework installs. But since the install should be rare, this quick fix is worth the time hit.

Failing flib tests have nothing to do with this script

Reviewed By: @ptarjan

Differential Revision: D1053633
2013-11-13 14:10:34 -08:00
Eugene Letuchy d25f3414a7 teach array_push about collections
Straight forward for Vectors and Sets: continue to throw
 exceptions for mapping types. ## array_push ## takes its array
 parameter as a reference, so the semantics are very close to a
 collection helper function.

Reviewed By: anietoro

Differential Revision: D1049841
2013-11-13 13:36:58 -08:00
Jordan DeLong 87addf0293 Remove a few dead functions from runtime.cpp
Reviewed By: @ottoni

Differential Revision: D1051475
2013-11-13 13:36:58 -08:00
Mike Magruder 6ecd0c9318 Minor optimization to the common path in hhvm extension stubs
Reduce the number of instructions needed on what ought to be the most common path on some of the simpler extension stubs. For calls to functions on this_ with no locals the tests in free_frame_locals_inl and friends were redundant. Provided a path to avoid those. Also out-lined a bit of code which should be more rare to try to save a little code size, and added some LIKELY/UNLIKELY markers. Switched a memcpy to a struct assignment. Looking at the asm output for th_10WaitHandle_getWaitHandle() shows a leaner and straighter path after the call thru to the return. The difference bewtween the memcpy and the struct assignment is (strangely) slightly different register scheduling which produces what I imagine could be fewer stalls.

Reviewed By: @jdelong

Differential Revision: D1051867
2013-11-13 13:36:57 -08:00
Joel Marcey f80c9b89bb Allow Zend to be used to run the unit tests for the frameworks
This gives the option to allow zend to be used to run the framework unit tests. This could be good for comparison purposes or to whitelist tests for HHVM that Zend also fails. Right now, we specify the path to the Zend binary. Later, we could see about using env variables or something to retrieve it.

Reviewed By: @ptarjan

Differential Revision: D1053279
2013-11-13 13:36:57 -08:00
bsimmers d7496a2fad Fix whitespace error in expect file
we think it was arc land's fault

Reviewed By: @jdelong

Differential Revision: D1053214
2013-11-13 13:36:57 -08:00
Rachel Kroll 6f3319f881 Clean up lingering elements of old file-cache API
Fix callers which depended on old API, and drop compat hacks

Reviewed By: bmaurer

Differential Revision: D1038433
2013-11-13 13:36:56 -08:00
Joel Marcey aa7f6646b2 Add proxies to our testing
We may be failing tests because the test needs access to the outside world, but we cannot get there due to the default firewall behavior. Provide the proxy info as part of the proc_open command to run the tests.

Also fixed a "thumb" problem. Better to rely on the contents of the expect file vs the out file to see if things ran as expected instead of setting variables all over the place.

Reviewed By: @ptarjan

Differential Revision: D1053079
2013-11-13 13:12:42 -08:00
Fred Emmott 1388a11eb5 Reimplemented RecursiveIteratorIterator
RecurisveIteratorIterator's original reverse engineer from lack
of PHP.net documentation had some parity differences -- make it better.

Closes #1260
Closes #1266

Reviewed By: @ptarjan

Differential Revision: D1052707

Pulled By: @scannell
2013-11-13 13:12:38 -08:00
Sean Cannella 0f5bf20761 Fix GCC 4.7.x compilation issue with lambda
GCC 4.7.x on Amazon Linux AMI compilation results in the linker
being unable to find the lambda so de-lambdify it.

Closes #1264

Reviewed By: @ptarjan

Differential Revision: D1052778
2013-11-13 13:12:33 -08:00
Drew Paroski de2b766540 Fix code path that can overflow the native stack
We had a bug where a PHP program can infinitely recurse in a certain way
that doesn't hit any of our native stack overflow checks and causes the
process to segfault. Below I've included a snippet of the callstack that
caused HHVM to crash.

The fix is to make invokeFunc(), invokeFuncFew(), and invokeContFunc()
unconditionally perform a stack overflow check for the native stack. I
tried to keep the fix minimal and non-invasive so that we can get this
hotfixed if needed.

  #0  0x00000000032ba2ef in malloc ()
  #1  0x000000000257401e in HPHP::Util::canonicalize(char const*, unsigned long, bool) ()
  #2  0x0000000001c15f0e in HPHP::resolve_include(HPHP::String const&, char const*, bool (*)(HPHP::String const&, void*), void*) ()
  #3  0x0000000001bd0327 in HPHP::Eval::resolveVmInclude(HPHP::StringData*, char const*, stat*) ()
  #4  0x0000000001fe47d0 in HPHP::VMExecutionContext::lookupPhpFile(HPHP::StringData*, char const*, bool*) ()
  #5  0x0000000001fe521a in HPHP::VMExecutionContext::evalInclude(HPHP::StringData*, HPHP::StringData const*, bool*) ()
  #6  0x0000000001c17231 in HPHP::AutoloadHandler::Result HPHP::AutoloadHandler::loadFromMap<HPHP::ConstantExistsChecker>(HPHP::String const&, HPHP::String const&, bool, HPHP::ConstantExistsChecker const&) ()
  #7  0x0000000001c174ed in HPHP::AutoloadHandler::autoloadConstant(HPHP::StringData*) ()
  #8  0x00000000020c1c73 in HPHP::Unit::loadCns(HPHP::StringData const*) ()
  #9  0x0000000001f1d10e in HPHP::Transl::lookupCnsHelper(HPHP::TypedValue const*, HPHP::StringData*, bool) ()
  #10 0x000000002827f855 in ?? ()
  #11 0x00000000026e566e in enterTCHelper ()
  #12 0x0000000001f35ef0 in HPHP::Transl::TranslatorX64::enterTC(unsigned char*, void*) ()
  #13 0x0000000002018004 in HPHP::VMExecutionContext::enterVM(HPHP::TypedValue*, HPHP::ActRec*) ()
  #14 0x000000000201821c in HPHP::VMExecutionContext::reenterVM(HPHP::TypedValue*, HPHP::ActRec*, HPHP::TypedValue*) ()
  #15 0x0000000002018612 in HPHP::VMExecutionContext::invokeFunc(HPHP::TypedValue*, HPHP::Func const*, HPHP::Array const&, HPHP::ObjectData*, HPHP::Class*, HPHP::VarEnv*, HPHP::StringData*, HPHP::VMExecutionContext::InvokeFlags) ()
  #16 0x0000000001c146d0 in HPHP::vm_call_user_func(HPHP::Variant const&, HPHP::Array const&, bool) ()
  #17 0x0000000001c17107 in HPHP::AutoloadHandler::Result HPHP::AutoloadHandler::loadFromMap<HPHP::ConstantExistsChecker>(HPHP::String const&, HPHP::String const&, bool, HPHP::ConstantExistsChecker const&) ()
  #18 0x0000000001c174ed in HPHP::AutoloadHandler::autoloadConstant(HPHP::StringData*) ()
  #19 0x00000000020c1c73 in HPHP::Unit::loadCns(HPHP::StringData const*) ()
  #20 0x0000000001f1d10e in HPHP::Transl::lookupCnsHelper(HPHP::TypedValue const*, HPHP::StringData*, bool) ()
  #21 0x000000002827f855 in ?? ()
  #22 0x00000000026e566e in enterTCHelper ()
  #23 0x0000000001f35ef0 in HPHP::Transl::TranslatorX64::enterTC(unsigned char*, void*) ()
  #24 0x0000000002018004 in HPHP::VMExecutionContext::enterVM(HPHP::TypedValue*, HPHP::ActRec*) ()
  ...
  #28992 0x0000000001c174ed in HPHP::AutoloadHandler::autoloadConstant(HPHP::StringData*) ()
  #28993 0x00000000020c1c73 in HPHP::Unit::loadCns(HPHP::StringData const*) ()
  #28994 0x0000000001f1d10e in HPHP::Transl::lookupCnsHelper(HPHP::TypedValue const*, HPHP::StringData*, bool) ()
  #28995 0x000000002827f855 in ?? ()
  #28996 0x00000000026e566e in enterTCHelper ()
  #28997 0x0000000001f35ef0 in HPHP::Transl::TranslatorX64::enterTC(unsigned char*, void*) ()
  #28998 0x0000000002018004 in HPHP::VMExecutionContext::enterVM(HPHP::TypedValue*, HPHP::ActRec*) ()
  #28999 0x000000000201821c in HPHP::VMExecutionContext::reenterVM(HPHP::TypedValue*, HPHP::ActRec*, HPHP::TypedValue*) ()
  #29000 0x0000000002018612 in HPHP::VMExecutionContext::invokeFunc(HPHP::TypedValue*, HPHP::Func const*, HPHP::Array const&, HPHP::ObjectData*, HPHP::Class*, HPHP::VarEnv*, HPHP::StringData*, HPHP::VMExecutionContext::InvokeFlags) ()
  #29001 0x0000000001c146d0 in HPHP::vm_call_user_func(HPHP::Variant const&, HPHP::Array const&, bool) ()
  #29002 0x0000000001c17676 in HPHP::AutoloadHandler::Result HPHP::AutoloadHandler::loadFromMap<HPHP::ClassExistsChecker>(HPHP::String const&, HPHP::String const&, bool, HPHP::ClassExistsChecker const&) ()
  #29003 0x0000000001c17a57 in HPHP::AutoloadHandler::invokeHandler(HPHP::String const&, bool) ()
  #29004 0x00000000020cb504 in HPHP::Unit::loadClass(HPHP::NamedEntity const*, HPHP::StringData const*) ()
  #29005 0x000000000203247e in void HPHP::VMExecutionContext::dispatchImpl<2>(int) ()
  #29006 0x000000000203ef43 in HPHP::VMExecutionContext::dispatchBB() ()
  #29007 0x0000000001f35f70 in HPHP::Transl::TranslatorX64::enterTC(unsigned char*, void*) ()
  #29008 0x0000000002017ed7 in HPHP::VMExecutionContext::enterVM(HPHP::TypedValue*, HPHP::ActRec*) ()
  #29009 0x000000000201888d in HPHP::VMExecutionContext::invokeFunc(HPHP::TypedValue*, HPHP::Func const*, HPHP::Array const&, HPHP::ObjectData*, HPHP::Class*, HPHP::VarEnv*, HPHP::StringData*, HPHP::VMExecutionContext::InvokeFlags) ()
  #29010 0x0000000002018ea0 in HPHP::VMExecutionContext::invokeUnit(HPHP::TypedValue*, HPHP::Unit*) ()
  #29011 0x0000000001c15964 in HPHP::invoke_file(HPHP::String const&, bool, char const*) ()
  #29012 0x0000000001c19a52 in HPHP::include_impl_invoke(HPHP::String const&, bool, char const*) ()
  #29013 0x0000000001c5d883 in HPHP::hphp_invoke(HPHP::ExecutionContext*, std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > const&, bool, HPHP::Array const&, HPHP::VRefParamValue const&, std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > const&, std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > const&, bool&, std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> >&, bool, bool, bool) ()
  #29014 0x0000000001b2659e in HPHP::RPCRequestHandler::executePHPFunction(HPHP::Transport*, HPHP::SourceRootInfo&, HPHP::RPCRequestHandler::ReturnEncodeType) ()
  #29015 0x0000000001b285d3 in HPHP::RPCRequestHandler::handleRequest(HPHP::Transport*) ()
  #29016 0x0000000001b6b85b in HPHP::XboxWorker::doJob(HPHP::XboxTransport*) ()
  #29017 0x0000000001b669a3 in HPHP::JobQueueWorker<HPHP::XboxTransport*, HPHP::Server*, true, false, HPHP::JobQueueDropVMStack>::start() ()
  #29018 0x000000000252c127 in HPHP::AsyncFuncImpl::ThreadFunc(void*) ()
  #29019 0x00007f1ce3787f88 in start_thread (arg=0x7f1c377ff700)

Reviewed By: @jdelong

Differential Revision: D1052293
2013-11-13 13:12:29 -08:00
Nicholas Ormrod 26c966423f rm tr1
C++11 has standardized the TR1 implementation; the latter
should now be purged.

With the deprecation of gcc-4.6, we have full C++11 support and are
capable of moving off of tr1. Further, moving to gcc-4.8 with tr1
causes some compilation issues, incentivising an immediate switch.

== How ==

  echo A | codemod --extensions h,cpp,cc,d,tcc 'std::tr1::' 'std::'
  echo A | codemod --extensions h,cpp,cc,d,tcc 'tr1::' 'std::'
  echo A | codemod --extensions h,cpp,cc,d,tcc 'include\s*<tr1/' 'include <'
  echo A | codemod --extensions h,cpp,cc,d,tcc '\s*namespace tr1 = std::tr1;\n' ''
  echo A | codemod --extensions h,cpp,cc,d,tcc '\s*using namespace tr1;\n' ''
  echo A | codemod --extensions h,cpp,cc,d,tcc 'using namespace std::tr1;' 'using namespace std;'

Performing
  ls | grep -v third-party | xargs egrep --color=auto -RIws "tr1"
yields a few non-comment results in
FacebookUpdate/windows/omaha/third_party/gtest/include/gtest/ and
facer/engine/worker/gearmand_0.11/ (seems like non-fb code), some
html (which has not been changed), ti/etc/wrapper.py (this looks like
some compatibility code), and linters/cpplint/ (which seem acceptable).

There are a few files which use tr1 legitimately. Specifically, google
value-parameterized tests require tr1::tuple, and do not work with
std::tuple. Fortunately, these are all cpp test files, not headers.
These files have had their codemod changes reverted.

tr1::functions may be initialized with NULL. std::function makes this
explicit and only allows construction from a newfangled nullptr_t. Clang
is very strict about this, so some NULLs needed to be changed to nullptrs.

== HPHP ==

Most of the non-codemod changes were to hphp. hphp needed to specialize
some hash functions in namespace std::tr1; the tr1 level has been
removed and now-duplicate definitions have been fixed.

hphp/tools/tc-print/perf-events.h makes use of std::tr1::array::assign,
which is no longer a standard function. Uses of assign have now been
replaced with fill. Of note, the arrays are of integral type, and so
slight differences in copy/move/delete semantics between fill and assign
should be irrelevant.

Reviewed By: @andrewjcg

Differential Revision: D1052036
2013-11-12 10:33:08 -08:00
steffen 772f598ff6 PDOStatement::queryString not set in all cases
PDOStatement::queryString right now is not being set when using
 the regular PDOStatement. If you use PDOStatement you don't want the
 constructor to be called, but you want queryString to be set in any
 case.

Closes #1211
Closes #1263

Reviewed By: @ptarjan

Differential Revision: D1051402

Pulled By: @scannell
2013-11-12 10:30:14 -08:00
Alex Malyshev 0c796cec44 Revert "Implement PDO::sqliteCreateFunction"
This reverts commit fc7fc47221308572e34e00b22d96773a1d18d051.
Was breaking open source build.

Reviewed By: @ptarjan

Differential Revision: D1052342
2013-11-12 10:30:10 -08:00
Joel Marcey 7af3cb978f Create classes for the frameworks
A fairly sizeable design change. Now all frameworks are subclasses of a master abstract Framework class. This makes special casing better and easier (e.g. Pear). And it is just better code, I think, for long term maintainability.

Reviewed By: @ptarjan

Differential Revision: D1049900
2013-11-12 10:30:01 -08:00
Paul Tarjan 6d0e85f4e3 Don't serialize Objects in ReflectionClass
Objects can change out from under this caching (dynamic properties) so this is safest. If it turns out to be perf critacl we can cut the data into cacheable and not. But then we'll have it figure out what key to use, since serializing it isn't in the contract of this class.

Reviewed By: @alexmalyshev

Differential Revision: D1051775
2013-11-12 10:29:57 -08:00
Paul Tarjan 3105114ae5 print file name
nice to have the name of the test at least

Reviewed By: @JoelMarcey

Differential Revision: D1052179
2013-11-12 10:29:52 -08:00
Stephen Chen b8cca52a9a Log requests that were timed out while queuing to access.log
Previously when we timeout requests that's been sitting on the queue for too
long, we just return 503 to the client on the transport. In addition to that, we
should log the request in access.log

Reviewed By: afrind

Differential Revision: D1033156
2013-11-12 10:29:48 -08:00
Edwin Smith 4c74bd2976 Remove HOT_FUNC
These macros are NOPs now, due to D1046368.  Remove them entirely.

Reviewed By: @markw65

Differential Revision: D1050690
2013-11-12 10:29:26 -08:00
Drew Paroski 779ce103ea Update unserialize to support moving all collections to a namespace
This diff extends the approach from D1031058 so that unserialization is
both forwards/backwards compatible with migrating all collection classes
to the HH namespace.

Reviewed By: anietoro

Differential Revision: D1050299
2013-11-12 10:24:14 -08:00
Jordan DeLong 60fcacb5f7 Some tweaks to conv_10
Some parameters were unused, and the length output parameter
can be sent back in a register.

Reviewed By: @edwinsmith

Differential Revision: D1050294
2013-11-12 10:24:10 -08:00
Jordan DeLong 34fd7cb844 Fix an issue with methodCacheSlowerPath if Fatal == false
After we store the null Func, it was setting an invName on
the ActRec even though it's not a magic call.  It would also update
the MCE as if it were magic.  I'm not sure if this could've caused a
bug (maybe someone would treat the invName as a VarEnv, since there
should never be an invName on a non-prelive actrec?)

Reviewed By: @bertmaher

Differential Revision: D1050301
2013-11-12 10:24:05 -08:00
Jordan DeLong f11209f4c4 Add string_data_eq_same function object
Similar to string_data_same, except uses exact equality first.

Reviewed By: @scannell

Differential Revision: D1048085
2013-11-12 10:23:56 -08:00
Yumikiyo Osanai 0d3f4092d3 APC shouldn't show as loaded when disabled
This modifies get_loaded_extensions() to not show the APC
extension when Server::APC::EnableApc is false.

Closes #1103
Closes #1262

Reviewed By: @JoelMarcey

Differential Revision: D1050685

Pulled By: @scannell
2013-11-12 10:23:52 -08:00
Jordan DeLong 8498e97562 Fix performance of array operator+= when lhs has refcount of 1
The change to make this unconditionally allocate a new array
changes big-O behavior of user code in some situations.  Thanks to
lesha and andrewparoski for catching this.  An equivalent case for
array_merge shouldn't be possible because an inc ref always happens to
pass it to the builtin.

Reviewed By: @paroski

Differential Revision: D1046251
2013-11-12 10:23:47 -08:00
Jordan DeLong 05718fd22c Fix build--redefinition of s_storage
Reviewed By: @edwinsmith

Differential Revision: D1050880
2013-11-12 10:23:43 -08:00
Edwin Smith abfb1b0684 Streamline findForNewInsert and copy/grow loops.
Remove the inline restrictions from findForNewInsert(), and
pass in table & mask so the loads from m_tableMask and m_hash
can be hoisted out of the hashtable init loops in Grow & Copy.
Also, replace memcpy/memset with loops that operate on words
at a time. (no alignment checks, even #s of words).

Reviewed By: @jdelong

Differential Revision: D1047021
2013-11-12 10:23:38 -08:00
Paul Tarjan 3c4ba6d1e6 make (array) of ArrayObject return the contents
I originally tried to use `o_get` but that isn't const, so I added a const version.

A side effect is `var_dump` of an ArrayObject now shows the inner array. Are we cool with that? I like it.

I also tried to move this class down to C++ but that is too much work for this.  @sgolemon is there an easy way to have the class in C++ but most of the impl in PHP?

Reviewed By: @jdelong

Differential Revision: D1041009
2013-11-12 10:23:34 -08:00
seanc c6382b6c23 CMake fix for GCC 4.7.x
Summary: Fix GCC 4.7.x build on some platforms for the following error:
error: ‘sleep_for’ is not a member of ‘std::this_thread’

Closes #1264
2013-11-11 15:58:54 -08:00
Sean Cannella 02ad508647 Disable FastCGI on aarch64
Summary: FastCGI doesn't currently build on aarch64 due to lack of Thrift support, disable it.

Reviewed By: @ptarjan
2013-11-11 04:47:53 -05:00
Alan Frindell 9fd97af110 Fix LibEventServer takeover
I refactored the logic here and missed a case that sets m_accept_socket back to -1 for a server that takes over.  This doesn't affect it's operation, but makes it unable to yield its fd to the next server (eg: 2nd gen takeover was busted)

Reviewed By: @paroski

Differential Revision: D1050529
2013-11-11 09:51:18 -08:00
Alan Frindell e5e065c8cf admin endpoint to change the log level
This is super useful for debugging ProxygenServer

Reviewed By: @jdelong

Differential Revision: D1049645
2013-11-11 09:51:11 -08:00
Rachel Kroll be19d77a4f Accept paths without leading /, too
Paths without a leading / were being rejected by MakePathList.
This changes the code to match the original FileCache::writeDirectories
logic.  It also drops the "return the filename, too" scheme since the only
call site just throws it out anyway.

Reviewed By: @paroski

Differential Revision: D1050552
2013-11-11 09:51:07 -08:00
Jordan DeLong feeda44dd0 Remove CSE flag from LdClsCachedSafe
If this instruction returns null, it's not safe to CSE it if
something in between may have defined the class.

Reviewed By: @markw65

Differential Revision: D1050386
2013-11-11 09:50:59 -08:00
Jordan DeLong d4ac83521a Translate InstanceOf
Mostly can use opcodes we've made for InstanceOfD, with a few
other additions.

Reviewed By: @markw65

Differential Revision: D1050261
2013-11-11 09:50:56 -08:00
Drew Paroski e2af194cf2 Fix reserialize() to properly handle the 'V' and 'K' serialization types
We hit an APC-related bug where reserialize() was being called on a
serialized collection during HHVM startup (when reading APC prime values
from a file), and this caused HHVM to fall over.

This diff fixes reserialize() and adds some test cases and comments.

Reviewed By: @markw65

Differential Revision: D1050281
2013-11-11 09:50:21 -08:00
Jordan DeLong 5f2af563e0 Remove generic dtor helper stub
It appears this doesn't help us in HHIR.

Reviewed By: @ottoni

Differential Revision: D1047133
2013-11-11 09:48:28 -08:00
Jordan DeLong fcc5e960ba Remove object data vtable
This is feasable now, after all the steps taken toward it
earlier.

Some subclasses still use vtables, so now we now have to take care to
do correct casts between ObjectData* and c_Foo*'s.  (HNI should
eventually let us change the c_Foos so they don't derive from
ObjectData at all.)  This diff changes things so that we have a custom
instance delete function (this replaces the late-bound ~ObjectData), a
bit in the object attributes that indicates whether it's got a native
subclass, and some additional metadata in PreClass telling us the
offset of the ObjectData subobject.  A variety of extension
destructors were also moved to headers so they could be inlined in the
appropriate delete_Foo functions (their only caller).

Reviewed By: @jano

Differential Revision: D1046763
2013-11-11 09:48:24 -08:00
Jordan DeLong 8efed9f7c9 Move o_properties out of ObjectData to side table
Pessimize dynamic properties in favor of smaller objects.
This goes with removing the vtable for ObjectData.

Reviewed By: @swtaarrs

Differential Revision: D1046746
2013-11-11 09:48:20 -08:00
Bert Maher e9dd65bffa FPushCuf: Optimize the case where callable is an (obj, staticstr)
The pattern call_user_func(array($obj, "staticString"), ...)
is pretty common, and it's basically the same as FPushObjMethodD
except it warns instead of fataling when the method is not defined.
Catch this pattern and turn it into a similar IR sequence, and add a
template flag to methodCacheSlowPath to warn instead of fataling.

Reviewed By: @swtaarrs

Differential Revision: D1042143
2013-11-11 09:48:16 -08:00
bsimmers 4c192e8bcc Clean up types of Block::back and Block::front
They returned IRInstruction*, while dereferencing a Block::iterator
gives IRInstruction&. This diff changes it to be consistent with every other
container. I also changed it so you can't get an IRInstruction& from a const
Block*. Luckily no code appeared to be depending on that.

Reviewed By: @jdelong

Differential Revision: D1049640
2013-11-11 09:48:12 -08:00
mwilliams 2bbc51c8a1 Get rid of global register variable in function-entry-helpers
This rewrites some helpers to avoid using the global
rbx register. This is needed for lto support (or at least, we
would have to compile function-entry-helpers.cpp with lto
off). Its also needed if we want to compile with clang, and it
will help with the arm port.

This adds a few new arm failures, but also fixes some existing bugs.

Reviewed By: @jdelong

Differential Revision: D1045712
2013-11-11 09:48:08 -08:00
Alex Malyshev b7712156bf Move warning in gc_collect_cycles() under HHSyntax
Was causing tests to fail in Magento2

Reviewed By: @scannell

Differential Revision: D1048980
2013-11-09 06:46:02 -08:00
Alex Malyshev 37acf16916 Have ElemDObject treat ArrayObject like an array
Corrects the case when a SetM is performed on an ArrayObject
that holds an array with a ref count of 1.

Reviewed By: @ptarjan

Differential Revision: D1048713
2013-11-09 06:45:58 -08:00
Eugene Letuchy 714a255691 reflection: better tests for xhp reflection
... and expect file built from correct branch this time.

Reviewed By: @scannell

Differential Revision: D1049263
2013-11-09 06:45:54 -08:00
Joel Marcey 7c8a387130 Move back to a fgets model and clean up test analyzing a bit
Since we determined that fgetc didn't solve deadlocking, and we just blacklisted those tests instead, we go back to fgets.

Also, clean up the way we analyze tests and their statuses.

PEAR is flaky. I don't think it is any atomicity or overwrite problem with the script. I think it might be the fact that we are running these things with separate processes. Or the tests are flaky. Either way we need a serial mode.

Reviewed By: @ptarjan

Differential Revision: D1049044
2013-11-09 06:45:50 -08:00
Eugene Letuchy 75b7cfeb46 correct undoing xhp name mangling in type_annotation
... this code should be the inverse of
 ScannerToken::xhpLabel.

Reviewed By: @dariorussi

Differential Revision: D1039358
2013-11-09 06:45:46 -08:00
Julius Kopczewski 7d8796a4c3 Fixing OSX build.
This is an internal part of the fix that allows HHVM to compile
under OS X.

Reviewed By: @scannell

Differential Revision: D1048727
2013-11-09 06:45:37 -08:00
Stephen Chen d47e3bde5f More improvements to the test framework for job queue
- simulate random arrival of events.
- keep track of request queue time and wall time for each request.
- keep track of the max queue time and max load.
- added ability to add a padding to the time to simulate random delays.
- compute various statistics for queuing time and wall time.

Reviewed By: rkroll

Differential Revision: D1044762
2013-11-09 06:45:17 -08:00
Joel Marcey 846da77cb8 Modify calculation formula and a bit of clean up
Modifying the calculation formula to take into account blacklisted tests as failures.

Reviewed By: @ptarjan

Differential Revision: D1048288
2013-11-09 06:45:08 -08:00
seanc 773a4cd620 Fix fastcgi build break on OS X
Summary: Disable fastcgi compilation on OS X due to missing dependencies
for the moment.

Reviewed By: @julk
2013-11-08 17:12:20 -08:00
seanc a596e67ce0 Add libboost-thread to Travis dependencies
Summary: With the fastcgi implementation we now depend on
libboost-thread so add it to the list of Travis dependencies.
2013-11-08 09:36:52 -08:00
Sean Cannella c47ea09d91 Merge pull request #1244 from EloB/configure_ubuntu_auto_yes
Added auto yes to apt-get install in configure_ubuntu_12.04.sh
2013-11-08 08:41:49 -08:00
Drew Paroski 0641b1d9e3 Revert "Fix /stop command issued when hhvm can't bind port"
This reverts D944849

Reviewed By: @bertmaher

Differential Revision: D1047984
2013-11-08 04:54:32 -08:00
Julius Kopczewski 6b1aaf3e87 Fixing changes in $_SELF logic.
Reverted unintentional changes in $_SELF computation logic.

Reviewed By: @ptarjan

Differential Revision: D1047953
2013-11-08 04:54:31 -08:00
Joel Marcey af46513d6a Blacklist some test files causing deadlocking issues
A few test files from a few frameworks are causing deadlocking issues with the script. Blacklist them. Deal with them later.

Reviewed By: @ptarjan

Differential Revision: D1047939
2013-11-08 04:54:31 -08:00
Joel Marcey 83fb9cfadc Miscellaneous fixes: add newlines back, remove specific user path info, and help message update
Removing the final newlines from the expect files was premature and probably a mistake.

http://stackoverflow.com/questions/729692/why-should-files-end-with-a-newline

So, leave it to clients/upstream to deal with newlines at the end of the file.

Also, do not print user path info out in expect files (or other files). e.g., no joelm

Also, list frameworks in help message when specifying invalid ones

Reviewed By: @ptarjan

Differential Revision: D1045907
2013-11-08 04:54:31 -08:00
Alex Malyshev ea9704e611 Initial implementation of ReflectionClass::getDefaultProperties()
We weren't tracking the default values of properties in
ReflectionProperty. Unfortunately this diff only fixes the issue for
classes that don't use ClassInfo, so builtin classes will still break.
Fixing them will be a separate diff.

Also replace old for loops with range-for

Reviewed By: @ptarjan

Differential Revision: D1043255
2013-11-08 04:46:33 -08:00
Alex Malyshev 19761000c7 RecursiveIteratorIterator must be constructed with a Traversable
This is Zend's behavior, and zf2 reflection tests check this

Reviewed By: @ptarjan

Differential Revision: D1045288
2013-11-08 04:46:29 -08:00
Jordan DeLong aed54167d1 Fix: fb_rename_function of extract disabled the wrong direction
This disabled making new functions named 'extract', which
doesn't work because extract already exists.  We want to disable
allowing creating new functions that have the behavior of extract.

Reviewed By: danielm

Differential Revision: D1042932
2013-11-08 04:46:21 -08:00
Rachel Kroll 6340ab6f36 Unit tests for mem-file
Unit tests for mem-file.

Reviewed By: bmaurer

Differential Revision: D1040720
2013-11-08 04:46:12 -08:00
Edwin Smith ac36d7a49c Demallocify md5
This refactors the MD5 code a bit to avoid forcing the use of malloc.
Now, the raw MD5 api unconditionally gives back a 16-byte digest,
and we have wrappers to convert to std::string and String, respectively.

Reviewed By: @jdelong

Differential Revision: D1046220
2013-11-08 04:46:07 -08:00
Jan Oravec e2a30d9af4 Unit test: do not assume existence of Static*WaitHandle::create() functions
Use async functions to generate Static*WaitHandles. The explicit methods
to do so will be gone soon.

Reviewed By: @billf

Differential Revision: D1046534
2013-11-08 04:45:59 -08:00
Alex Malyshev 3e87af5430 Give ArrayObject's fields default values
Magento2 (and possibly other frameworks) end up making classes
that extend ArrayObject but never call its constructor. This works
under Zend so it should work under us as well.

Reviewed By: @scannell

Differential Revision: D1045913
2013-11-08 04:45:54 -08:00
Guilherme Ottoni 24fa57241c Inline small cold functions into hot ones
I noticed some missed opportunities for inlining were because the
callee was not marked as hot, but the caller was.  There's a check to
prevent inlining in such case, which kind of makes sense -- the call
may be in a cold path.  However, in some cases the callee is not
marked as hot probably just because it's too small.  And if the
function is small enough it's better to inline it anyway -- they code
may get smaller.  So I added a callee code-size threshold below which
inlining is always allowed.

I did some experiments with different values for the new threshold,
and also the previously existing HHIRInliningMaxCost, and set them to
what seems best these days.

Reviewed By: @jdelong

Differential Revision: D1044965
2013-11-07 05:11:42 -08:00
Eugene Letuchy 4b9cf93aca parity: make ZipArchive Not Implemented errors informative
... throwing ##"Not implemented is not implemented"## does
 not cover oneself in glory. Easy fix with a few emacs macros

Reviewed By: @ptarjan

Differential Revision: D1044243
2013-11-07 05:11:38 -08:00
Eugene Letuchy cd90ada2ce parity: move gc_enable warnings behind hip hop syntax
... and make gc_disable emit no warnings, since it's a 100%
 effective no-op.

Reviewed By: @ptarjan

Differential Revision: D1044225
2013-11-07 05:11:34 -08:00
Joel Marcey 4b4289d0f3 Sort the expect files alphabetically.
Let's sort the expect files alphabetically so any changes to them doesn't result in mega-diffs.... well, this will be the last mega diff to prime the expect files :)

Reviewed By: @ptarjan

Differential Revision: D1044747
2013-11-07 05:11:29 -08:00
bsimmers ef42b9fafb Add PushL for use in continuations
PushL pushes the value of a local on the stack and unsets it, avoiding
any refcounting operations. This is useful in Continuation::send and async
functions.

Reviewed By: @ottoni

Differential Revision: D1042054
2013-11-07 05:11:14 -08:00
bsimmers 1fa7056183 PHP integers are 64 bits
The fact that ArrayData::m_size is uint32_t complicated things a bit.

Reviewed By: @bertmaher

Differential Revision: D1043095
2013-11-07 05:11:09 -08:00
Stephen Chen 38190c61f3 unittest for doing a controlled simulation of job queue workload
A simple framework for doing a controlled simulation on job queue. Within this
set up, we can specify a duration for each request going through the system. The
request will have a fixed service duration of x ticks. We define our own
TickWorker that finishes the request after x ticks. We have a static global
logical clock we can then use to drive the simulation.

The next step is to generate a reasonable workload based on our real work
request latency distribution and run it through the system. After that, we can
simulate server side issues (ie. all reqeusts incur additional latency or small
percentage of request with very high latency).

The test case will help us select and fine tune the algorithm for doing queuing
and timeouts.

Reviewed By: rkroll

Differential Revision: D1043222
2013-11-07 05:11:04 -08:00
Sara Golemon 39ac07f4fb Remove generated file from repo 2013-11-06 14:40:22 -08:00
Paul Tarjan de8225a594 use a different config for frameworks
@elgenie had a good point that we don't want to turn on hiphop syntax for the frameworks.

Reviewed By: @elgenie

Differential Revision: D1044204
2013-11-06 11:08:55 -08:00
bsimmers 16ccd2e16d Move the rest of Type's methods into type.cpp
Reviewed By: @jdelong

Differential Revision: D1043399
2013-11-06 11:08:51 -08:00
Paul Tarjan a61dd82692 expose dynamic properties in reflection
ReflectionClass supports taking an object and should use the dynamic props from it. @alexmalyshev is going to send a diff about default, so we'll have to co-ordinate whoever lands first.

Reviewed By: @elgenie

Differential Revision: D1043099
2013-11-06 11:08:47 -08:00
Paul Tarjan d5679aa80a now isCallable won't die if there isn't a type_hint
Reviewed By: @dariorussi

Differential Revision: D1042437
2013-11-06 11:08:43 -08:00
Sean Cannella 7ecc6dfab6 HHProf: Support showing all allocations
Add a mode for HHProf where all allocations are shown. This
isn't helpful for leak tracking or looking at what memory is still
alive, but this allows visibility into allocation patterns that would
otherwise be hidden because they are balanced.

Reviewed By: @mikemag

Differential Revision: D1042696
2013-11-06 11:08:39 -08:00
Joel Marcey 48ceb22824 Use a different stream timeout approach
fgets was not working. stream_select seemed ok, but fgets seems to block anyway if only a certain amount of data is available without a newline. Use an fread(), character by character approach.

Reviewed By: @ptarjan

Differential Revision: D1043978
2013-11-06 09:29:20 -08:00
Paul Tarjan fb12616289 don't emit warning with empty haystack
zend doesn't emit a warning

Reviewed By: @alexmalyshev

Differential Revision: D1043427
2013-11-06 09:29:20 -08:00
Joel Marcey fa5b05e204 Fix "Nothing to do" errors coming from PHPUnit test suite
We were getting errors like: PHPUnit_Framework_Exception: HipHop Notice: Nothing to do. Either pass a .php file to run, or use -m server.

It had to do with running php in processes and passing php code via stdin. We need the php wrapper/symlink to hhvm instead of the explicit hhvm binary.

The fix was to fork phpunit, make a change to their getphpbinary() function to check for an environment variable that we then set in this script. Then we upstreamed that fix to the master phphunit branch and it was quickly accepted (that was nice!)

Also added @elgenie fork for Slim as well.

Reviewed By: @ptarjan

Differential Revision: D1043544
2013-11-06 09:29:19 -08:00
Paul Tarjan 5036732b47 cast instead of L
crossplatform

Reviewed By: @alexmalyshev

Differential Revision: D1043270
2013-11-06 09:29:19 -08:00
Surupa Biswas bbc5965894 Batched apc_store and apc_add support
Added support for passing arrays to apc_store/add instead of key,value pairs one at a time. Sharing an early
version to get code review feedback.

Reviewed By: @paroski

Differential Revision: D1037553
2013-11-06 09:29:19 -08:00
Bert Maher 405a9d6679 Remove StaticMethodCache::lookup, since lookupIR has supplanted it
It's dead, Jim.  Also rename lookupIR -> lookup, since
there's no distinction any more.

Reviewed By: @swtaarrs

Differential Revision: D1042980
2013-11-06 09:29:18 -08:00
Edwin Smith fe6b89cf5b Streamline string_replace()
I noticed this was hot in perf, so I did some standard streamlining:
- have the string functions use String(ReserveString) instead of malloc
- switch a std::vector to smart::vector
- inline the small String::replace() wrapper functions
- mark f_string_replace and string_replace() as HOT_FUNCTION

Reviewed By: @jdelong

Differential Revision: D1041907
2013-11-06 09:29:18 -08:00
Alex Malyshev 144ba6cce5 Implement PDO::sqliteCreateFunction
This function is already implemented as SQLite3::createFunction, however
PDO is expected to have it's own version of it as well. I leaked some of
the SQLite3 declarations over to PDO to get it to work.

Zend just duplicates all the functionality between PDO and SQLite3, for
instance 'php_sqlite3_func_callback' and 'php_sqlite3_callback_func' are
the same function just in different files...

Reviewed By: @ptarjan

Differential Revision: D1039095
2013-11-06 09:29:18 -08:00
bsimmers b59a8c407b Clean up codegen for InstanceOf
instanceOfHelper was just a thin wrapper around Class::classof. Do the
null check in the TC and call classof directly. I also get rid of a null check
in classof which trimmed down its assembly a bit.

Reviewed By: @jdelong

Differential Revision: D1042062
2013-11-06 09:29:18 -08:00
Sean Cannella d8cfc0420a Remove dead shared memory code
Removing dead shared (between processes) memory code and doc references

Reviewed By: @markw65

Differential Revision: D1042569
2013-11-06 09:29:17 -08:00
Joel Marcey c38100a138 Fix the timeout issues when running framework tests.
I was checking for false on stream_select; I needed to check for 0 instead.

Reviewed By: @ptarjan

Differential Revision: D1042557
2013-11-06 09:29:17 -08:00
aravind 549043294f Revert "Relax guard on input of SetM"
: This reverts commit 8bd12391c963659e70a46562776a9e6aeb842c7f.

Reviewed By: @ottoni
2013-11-06 09:29:17 -08:00
Drew Paroski c1967fa90a Wrap "test/slow/collection_classes/817.php" within a main() function
Eugene found some bugs with collections when he wrapped some of the our
collections tests inside a "main" method. These bugs have since been fixed,
so we can update collections tests that are not wrapped in "main" methods.

Reviewed By: @ptarjan

Differential Revision: D1041602
2013-11-06 09:29:16 -08:00
Julius Kopczewski e6b78bb278 Implement Fast CGI support
Split the monolithic functions preparing special variables such
as $_REQUEST or $_SERVER into multiple functions to enable feeding of
data from multiple sources. In case of FastCGI protocol, the values are
sent by the web server.

Import parts of proxygen and thrift.

Added #ifdef's to allow compilation with an unpatched version
of libevent library.

Reviewed By: @ptarjan

Differential Revision: D988737
Differential Revision: D1008756
Differential Revision: D1021808
Differential Revision: D1035231
2013-11-06 09:02:37 -08:00
Sara Golemon e4e0607370 Update folly submodule
Remove duplicate IOBufQueue from folly build
2013-11-05 17:40:27 -08:00
Sara Golemon 9680ccc24a Remove dead file 2013-11-05 17:40:27 -08:00
Sara Golemon 68cabf216a Remove RTLD_DEEPBIND from dlopen() call
It confuses TLS objects.

Closes #1174

Reviewed By: @scannell

Differential Revision: D1009729
2013-11-05 14:24:12 -08:00
Owen Yamauchi d65887fd2c Slightly relax FPushFunc's locals-destroying semantics
If the call has no arguments, it can't destroy locals, even if it's a
call to extract().

Reviewed By: @jdelong

Differential Revision: D1042425
2013-11-05 14:24:09 -08:00
Owen Yamauchi 39b3ab3075 Codegen for ConvArrToBool fast path
If it's not an NVTW, it's really quick to convert an array to a bool: is
m_size nonzero? The cold path is still a call to C++.

We can argue about codegen if you want. I could have the C++ helper
return a bool, get that into the dest register, and then jump over the
setcc, or do what I've done here.

Reviewed By: @edwinsmith

Differential Revision: D1040912
2013-11-05 14:23:56 -08:00
Cullen Walsh a6320cb4bc Allow generation of hack types in hhvm thrift extension
Look for a "format" key in the thrift spec array for collections (maps, vectors, sets). If the value is "collection", construct a Map/Vector/Set object rather than an array.

Reviewed By: @andrewcox

Differential Revision: D1025009
2013-11-05 14:23:41 -08:00
Paul Tarjan e5fbfabddd stop reporting negative numbers for memory
We were calling `newSlab` at statup and then `hphp_session_init` promptly calls `resetStats` setting it to 0. It looks like we should clear the stats when we clear the slab. That's a little scary for now, so I'm going to just make it non-zero.

Reviewed By: @jdelong

Differential Revision: D1041217
2013-11-05 14:23:37 -08:00
Jordan DeLong e4c2f9e280 Streamline method cache helpers
Make the fast path of the method cache slow path do a little
less work.

This was in part to see if the wouldCall logic could get simple enough
to make it a fast path unique stub in ahot.  This version of the code
was simple enough for me to translate to a unique stubs, which I tried
last night (the theory was that getting it on the first page of ahot
could help iTLB/icache), but it was in the noise.  I only did
methodCacheSlowPath(), so maybe it would only help if the whole thing
was pulled over, but I'm inclined to think that this suggests idea of
trying to move hot helpers to ahot stubs isn't very promising.

Reviewed By: @markw65

Differential Revision: D1039748
2013-11-05 14:23:33 -08:00
Jordan DeLong 0d9b67916c Remove null check from AtomicSmartPtr::operator->
I saw code doing null checks on the m_preClass in
target-cache.cpp's wouldCall(), but it turned out to be unreachable
code.

Reviewed By: @dariorussi

Differential Revision: D1039739
2013-11-05 14:23:28 -08:00
Mike Magruder 056301d824 Ensure ext_hotprofiler always closes main() with the data from when profiling was turned off
When we run out of log space while profiling, we close out the dangling stack with the last entry we have. This under-represents the functions left on the stack, which is fine, but also (sometimes greatly) under-represents main(), which is a pseudo-function intended to represent the entire profiling run. This change ensures that we always close out main() with data from when profiling was turned off, even if we run out of trace space.

Reviewed By: @swtaarrs

Differential Revision: D1040813
2013-11-05 14:23:20 -08:00
Edwin Smith 39d2a5f953 Streamline tvDupFlattenVars
Some callsites always pass nullptr, and some always pass non-null.
Also, we can make the whole thing smaller by rearranging the cases.

Reviewed By: @markw65

Differential Revision: D1041950
2013-11-05 14:23:08 -08:00
Alex Malyshev 012708bca5 Move sort comparators returning bools warning under HH syntax
Fixes a lot of errors in doctrine2.

Reviewed By: @ptarjan

Differential Revision: D1041273
2013-11-05 14:23:04 -08:00
Joel Marcey 9d0eaf9a15 Refactor SingleTest
SingleTest was a bit unwieldly. This hopefully refactors it a bit nicer. Also, found some output bugs that may have affected our runs.

Next is to sort the expect files so that we can change them without monster diffs

Reviewed By: @ptarjan

Differential Revision: D1041553
2013-11-05 14:22:56 -08:00
mwilliams d4d5106d3d Use sign bit for static ref count
Switches to using the sign bit to indicate that a refCount
is static, and rewrites the various decRef sequences to be:

  if (count == 1) release();
  else if (count > 1) --count;

Adds runtime options to allow experimentation with the exact strategy;
 - whether to load the count into a register (if one is available)
 - whether to use if (!--count) release(); if we don't need a static check
 - whether to skip using the register and just emit --count if we know
   its not static, and can't hit zero.

Also switcher various other static-bit checks to do byte tests on the
high byte, rather than word tests on the entier value.

Reviewed By: @edwinsmith

Differential Revision: D1012547
2013-11-05 14:22:48 -08:00
Paul Tarjan 715d7e0062 Make ReflectionParameter not completely wrong
@dariorussi what is this crazyness? Do you have a rewrite of this class? This is 100% insane.

Reviewed By: @dariorussi

Differential Revision: D1041883
2013-11-05 14:22:39 -08:00
Paul Tarjan 5d9c81fab1 fix ProxyArray::Escalate
this was a copy-paste bug that eagle-eye-@edwinsmith found

Reviewed By: @jdelong

Differential Revision: D1040832
2013-11-05 14:22:35 -08:00
Chad Horohoe b23bccfaeb Move functioning Zend test
Move functioning Zend test

Closes #1246

Reviewed By: @ptarjan

Differential Revision: D1041989

Pulled By: @scannell
2013-11-05 14:22:30 -08:00
Daniel Marinescu babd644466 Made fb_rename_function to not allow renaming to "extract".
fb_rename_function will not allow renaming to "extract".

Reviewed By: @jdelong

Differential Revision: D1041497
2013-11-05 14:22:26 -08:00
mwilliams eddaab5bcb Fix threading issues with fb_intercept
The first time we call a method, we add its flag to the
intercept table (so it can be enabled by future calls to intercept)
and then set the flag based on whether or not its intercepted in
the current thread.

That leaves a hole where thread a could call intercept,
thread b could call the function (setting the flag to zero,
because its not intercepted in thread b), and then thread a
would behave as if the function were not intercepted.

Fixed by using adding a flag to the global table to say whether
or not its ever been intercepted, and initializing the method's
flag from there.

Reviewed By: @jdelong

Differential Revision: D1039463
2013-11-05 14:22:18 -08:00
Sean Cannella c3c4ee838f Change CheckSymLink default to match Zend
CheckSymLink (following symlinks and making the realpath calls)
is the Zend behavior so we should default to this as well and allow
people to disable it for performance reasons instead of the inverse.

Depends on D1034342

Reviewed By: @ptarjan

Differential Revision: D1034354
2013-11-05 09:20:49 -08:00
Guilherme Ottoni b978890b9b Avoid DV initializer loop in prologues for small number of DVs
We were always generating a loop like:
     0xd800252: mov eax, 0x1
     0xd800257: sub rbx, 0x10
     0xd80025b: inc eax
     0xd80025d: mov byte ptr [rbx+0x8], 0x0
     0xd800261: cmp eax, 0x2
     0xd800264: jl 0xd800257
to set the DVs that didn't get a value passed in to Uninit.

This diff unrolls the loop for small number of values to be
initialized.

Reviewed By: @jdelong

Differential Revision: D1041394
2013-11-05 09:20:46 -08:00
aravind 71201e2933 Relax guard on input of SetM
Reviewed By: @ottoni

Differential Revision: D1041679
2013-11-05 09:20:42 -08:00
Sean Cannella 5d60ea9eaf Reduce default JIT structure sizes
Right now HHVM allocates about 1.2 GB of memory by default.
Reduce this by a factor of ~10 for a better experience with small
applications, VMs with limited memory, evaluation and testing purposes,
etc.

The configuration settings are available to change this to the previous
behavior is reproduced here for ease of access:

Eval {
  JitAHotSize = 4194304
  JitASize = 536870912
  JitAProfSize = 536870912
  JitAStubsSize = 536870912
  JitGlobalDataSize = 134217728
}

Reviewed By: @markw65

Differential Revision: D1034305
2013-11-05 09:20:37 -08:00
Cristian Hancila 0cd140154b Added async stack inspection and traversal to hphpd
Debugger commands 'up','down' and 'variable' now operate on the async
stack as well as the regular stack. If used in conjuction with 'where async'
the awaitable dependency stack is traversed instead of the regular stack
by the said commands.

Reviewed By: @mikemag

Differential Revision: D1034548
2013-11-05 09:20:33 -08:00
mwilliams 537a2ba1f4 Fix refCounting issues with various String functions
Some functions took a const String&, but assumed
that if the refCount was 1 they could destroy the parameter.

This is fine for calls from the vm, because it always refcounts
correctly, but can lead to surprising results for calls from c++
code.

It turns out that (for g++/x86 at least) the actual calling convention
for a function taking a String is identical to one taking a const String&
(ie its the caller's responsibility to pass a reference to a
temporary in the former case). So this diff just changes them
over to be String (which required a bit of hackery in the code to
generate the vm stubs). That fixes the issue for calls from c++, and
has no effect on calls from the vm.

Reviewed By: @jdelong

Differential Revision: D1040836
2013-11-05 09:20:29 -08:00
Paul Tarjan bce1718652 start supporting date.timezone INI setting
We need to initialize the timezone or else we get a warning in the logs. I could have added a -v option, but I want to start putting things in the INI files when they exactly correspond to a PHP ini setting.

I created a `php.ini` file just for the test runner and forced us to use it.

Reviewed By: @JoelMarcey

Differential Revision: D1040418
2013-11-05 09:20:25 -08:00
Niharika Marwah 8a7b741f2e Remove deprecated methods
Remove the deprecated methods hphp_thread_set_warmup_enabled/hphp_thread_is_warmup_enabled

Reviewed By: @ptarjan

Differential Revision: D1026245
2013-11-05 09:20:20 -08:00
Edwin Smith 6ccd766a74 Delete unused string_concat() and string_trim()
They are dead code.

Reviewed By: @bertmaher

Differential Revision: D1040044
2013-11-05 09:20:16 -08:00
Drew Paroski db77268a47 Small fix for ContSuspend* instructions
The ContSuspend* instructions were not marked as "terminal" (TF), and so
the bytecode emitter thought it was possible to these instructions to fall
through and there some unnecessary Null instructions being emitted for
"yield" expressions to satisfy asserts in the bytecode emitter.

This marks the ContSuspend* instructions as "terminal" and gets rid of the
unnecessary Null instructions that were being emitted.

Reviewed By: @jdelong

Differential Revision: D1039548
2013-11-05 09:20:12 -08:00
Dario Russi 37ba80ba8c Inline fast path for packed array get and isset
Teach the JIT to specialize the get and isset operations on packed arrays

Reviewed By: @bertmaher

Differential Revision: D1031551
2013-11-04 13:57:04 -08:00
Alex Malyshev 70a41e059e Don't fatal on null properties when using magic methods
Matches Zend's behavior of emitting a fatal error on properties that
start with \0 only if the object does not have the appropriate magic
method defined.

Reviewed By: @ptarjan

Differential Revision: D1032024
2013-11-04 13:56:56 -08:00
Drew Paroski 7119bff22c Fix Traversable
HHVM's instanceof operator was returning true when checking if an array was
an instance of the Traversable interface, and this was breaking some PHP
code out in the wild. This diff fixes HHVM so that the instanceof operator
returns false in such cases.

There are some existing hh files that require that "array() instanceof
Traversable" return true. To solve this, we introduce a new interface
named "HH\Traversable" and we change "instanceof" to return true when
checking if an array is an instance of \HH\Traversable, and we update the
parser so that it implicitly imports \HH\Traversable for hh files when we
are in the global namespace and there are no conflictly "use" statements.
To keep the interface hierachy coherent, the Iterator interface required
similar treatment.

Reviewed By: @ptarjan

Differential Revision: D1037748
2013-11-04 13:56:52 -08:00
Jordan DeLong 7dfea4e50d Change stubsCode to mainCode in ARM::emitFuncPrologueRedispatch
This is in mainCode in X64---figured I'd change it in case it
is easy to miss when we actually implement the stub.

Reviewed By: @scannell

Differential Revision: D1039633
2013-11-04 13:56:48 -08:00
Jordan DeLong 17380509be Better dispatch for rhs of array_merge and +
Specialize on array kinds.

Reviewed By: @markw65

Differential Revision: D1034616
2013-11-04 13:56:44 -08:00
Edwin Smith a4c7a7a0d0 Delete unused option ThreadingJit
It was dead

Reviewed By: @markw65

Differential Revision: D1039955
2013-11-04 13:56:39 -08:00
Owen Yamauchi 22fb60143f Fix a bug in my previous fix of SetL/BindL logic
Silly me, I thought that box() does sort of the opposite of unbox(). To
wit, I thought it would box Cells and pass through already-boxed stuff.
Turns out it assert-fails on already-boxed stuff.

Reviewed By: @swtaarrs

Differential Revision: D1038748
2013-11-04 13:56:35 -08:00
Kristaps Kaupe 52b7fa1c95 Add TypedResults for MySQL extension
Introduced MySQL TypedResults runtime parameter, which allows
switching from HHVM behavior of returning also ints and doubles from
MySQL results to Zend behavior of returning only strings and nulls.

Closes #1237
Closes #1238

Reviewed By: @ptarjan

Differential Revision: D1038046

Pulled By: @scannell
2013-11-04 13:56:31 -08:00
bsimmers 43ab3169d3 Use type aliases instead of inheritance in smart-containers.h
Because it's the right thing to do. We overrode the default
constructor for hash_map so I left that alone for now.

Reviewed By: @jdelong

Differential Revision: D1035287
2013-11-04 13:56:26 -08:00
Paul Tarjan 0f69678368 make preg_replace work with /e
Remove a lot of the HPHPc hacks and do real eval. I could have re-used the escaping but the code was a bit cleaner like this

Reviewed By: @markw65

Differential Revision: D1015443
2013-11-04 13:56:22 -08:00
aravind 2830cca4ed Refcount validator fix
Check countness of current SSATmp, not the original SSATmp for
refcount validation. Passthrough instructions like CheckType<Int>
can cause the countness to change.

Reviewed By: @ottoni

Differential Revision: D1038437
2013-11-04 13:56:14 -08:00
mwilliams 68bb74d226 Clean up object/resource destruction
More changes to avoid mulitiple copies of destruct
sequences, to make it easier to modify the incRef/decRef
code.

No intentional changes to behavior/performance

Reviewed By: @jdelong

Differential Revision: D1038763
2013-11-04 13:56:10 -08:00
Joel Marcey 29a7593652 Fix (Hopefully) the timeout/deadlock issue...
Some tests would deadlock, even with the specified timeout. So I added some more stream_select statements before appropriate fgets calls.

Reviewed By: @ptarjan

Differential Revision: D1039419
2013-11-04 13:56:05 -08:00
Jordan DeLong 1c07c73744 Avoid VerifyParamType on specialized object types, when possible
This can kick in if you inline a function, passing an
argument that came directly from AllocObj, but isn't measurable on the
site.

Reviewed By: @bertmaher

Differential Revision: D1038352
2013-11-04 13:56:01 -08:00
Jordan DeLong 123598b569 Fix a bug when lookupClsMethodHelper needs to fatal
It forgot to propagate the exception.

Reviewed By: @bertmaher

Differential Revision: D1039332
2013-11-04 13:55:57 -08:00
Joel Marcey fd17888ae8 Framework Script Refactoring #1
No change in functionality. Just some refactoring. Putting methods in classes. Common forking and bucketing method. Etc.

Next up:

Timeout bug
Alphebetize expect file
More refactoring

Reviewed By: @ptarjan

Differential Revision: D1039348
2013-11-04 13:55:52 -08:00
Edwin Smith 98d233f262 Support (gpr,gpr)=>xmm movs in shuffle2
If you turn off Precoloring without turning off XMM support,
stuff breaks due to not copying Cell values coming back from
calls, from (eax,edx) to whatever full xmm register was assigned.

Reviewed By: @ottoni

Differential Revision: D1037919
2013-11-04 13:55:48 -08:00
Eugene Letuchy 5c12c61de4 collections: teach implode() about collections
very straight-forward, since ##isContainer##,
 ##getContainerSize##, and ##ArrayIter## are already collection
 friendly.

Reviewed By: @paroski

Differential Revision: D1031865
2013-11-04 13:55:44 -08:00
Dario Russi 467da2a3df Reflection Zend compatibility fix for Relfection::getStaticProperties
getStaticProperties returns an array with propName => value and not a propName => propInfo

Reviewed By: @ptarjan

Differential Revision: D1033668
2013-11-04 13:55:39 -08:00
Guilherme Ottoni 1cfb1afa2f Dump IR after ref-count optimization when validation fails
Just that.

Reviewed By: aravind

Differential Revision: D1038415
2013-11-04 13:55:35 -08:00
Paul Tarjan cb52292f91 do normalizeNS in GetNamedEntity
Lets see if we can put this up to `GetNamedEntity`. It is a LOT cleaner this way and fixes the bug in the attached class.

I still need the helper as constants don't have `NamedEntities`.

Reviewed By: @markw65

Differential Revision: D1032816
2013-11-04 13:55:30 -08:00
Jordan DeLong 155b55fa10 Don't punt on Clone; call ObjectData::clone from TC
Reviewed By: @swtaarrs

Differential Revision: D1038227
2013-11-04 13:55:26 -08:00
Jordan DeLong a5e94b6ef5 Don't interp one {Class,Interface,Trait}Exists as much
Reviewed By: @swtaarrs

Differential Revision: D1038082
2013-11-04 13:55:21 -08:00
Jordan DeLong 3aa64638d9 Revert "Drop "de-const" cast hack from API migration"
This reverts commit 2678af0f83d35530c4285295419ea5ebcb79113d.

Reviewed By: @bertmaher

Differential Revision: D1038880
2013-11-04 13:55:12 -08:00
Olle Bröms 7e13f9c899 Added auto yes to apt-get install in configure_ubuntu_12.04.sh 2013-11-04 00:45:39 +01:00
mwilliams f1a5b3f2b0 Destructor cleanup
Reduce to a single implementation of the generic
dec-ref-and-destroy code.

RefData can never be static, so stop checking it

Reviewed By: @swtaarrs

Differential Revision: D1037810
2013-11-01 14:54:48 -07:00
Bert Maher 9138f0b6de Implement SetOpL for array arguments
A few hot call sites use this.

Reviewed By: @ottoni

Differential Revision: D1037492
2013-11-01 14:54:44 -07:00
Joel Marcey 7b5a122c6d Sort frameworks for test bucket breakup
Sort the frameworks vector so that we can have a general alphabetical order of test
running after we bucket them in threads.

Fix a couple of bugs (undefined variable and possible div by zero) too.

Reviewed By: @ptarjan

Differential Revision: D1038251
2013-11-01 14:54:40 -07:00
Jordan DeLong 29ed627bef Make AllocObj{,Fast} return a specialized object type
Reviewed By: @dariorussi

Differential Revision: D1032573
2013-11-01 14:54:32 -07:00
Mike Magruder 21b8e31e3b Release old arrays when we grow them while setting/unsetting elements
D988759 changed the way we reallocate arrays, and broke a previous optimization in SetNewElemArray and UnsetElemArray, causing memory leaks in a wide variety of cases. We got a very nice repro from the Firehose team. This fixes the test case in the referenced task, which can complete now with minimal memory use. I suspect this also explains a number of other OOM bugs which have been cropping up since the 10/25 release, and perhaps the extra swapping in v3 we've experienced since then.

Reviewed By: @jdelong

Differential Revision: D1038091
2013-11-01 14:54:28 -07:00
Edwin Smith a2c5dfa486 Add PhysLoc::numWords and rename SSATmp::numNeededRegs->numWords
This is just code cleanup; sometimes we care about the # of logical
words for a tmp or PhysLoc, (eg 2 for a TypedValue) and sometimes
we care about the physical locations assigned (eg 1 for FullXMM,
0 for a constant).  This separates the two a bit more clearly.

Reviewed By: @bertmaher

Differential Revision: D1037818
2013-11-01 14:54:24 -07:00
Jordan DeLong c122ac9394 Remove unused bool m_no_volatile_check
Always false.

Reviewed By: @markw65

Differential Revision: D1036977
2013-11-01 14:54:19 -07:00
Paul Tarjan bacc8cbfe4 actually remove temporary php_ini
I thought this was taken care of me for free. Nope.

Reviewed By: @alexmalyshev

Differential Revision: D1038214
2013-11-01 14:54:15 -07:00
aravind be95320b33 Don't decref Objects while sweeping
Per title

Reviewed By: @jano

Differential Revision: D1037445
2013-11-01 14:54:11 -07:00
Rachel Kroll cc400ca76a Drop "de-const" cast hack from API migration
Preserve const in mem-file
Track malloced pointer separately in mem-file

Reviewed By: bmaurer

Differential Revision: D1037894
2013-11-01 14:54:07 -07:00
mwilliams 21baad1c0f Fix user profiler for native funcs
Various places test func->info to determine whether a Func is a c++
builtin or not. Some of them need to include Native Funcs.

Rename Func::info to Func::methInfo to find all the uses, and spot
check them.

Reviewed By: @jdelong

Differential Revision: D1035915
2013-11-01 10:11:26 -07:00
Joel Marcey f714b0c3fa Fix forking problem when running individual tests
The script now preloads all of the tests for all of the specified frameworks (every test is retrieved with --all). Then we fork of threads, bucketing as necessary to keep things sane. This is instead of forking of a thread per framework and then more threads for the tests of each framework where we could get up to 1000+ instances of HHVM going (and that is bad).

Also fixed a bug on how we retrieve the actual tests.

Did a little more refactoring too.

Singled out two tests from zf2 that was causing some weird deadlocking. Don't run those. Figure out why and then take them out.

Reviewed By: @ptarjan

Differential Revision: D1037105
2013-11-01 09:16:20 -07:00
aravind 797de2403a Fix for readMetaData
In legacy mode, readMetaData should not modify the input
rtts, since these are shared with the tracelet's guards.

Reviewed By: @ottoni

Differential Revision: D1036751
2013-11-01 09:16:12 -07:00
Owen Yamauchi efc2a76205 Two little ARM fixes
- There were register "allocation" bugs in the closure code. First, the
  incref code was clobbering the address of the datum to incref with the
  refcount. Second, the closure prologue code was using rAsm2 to hold
  the closure's address, and that got clobbered by the fixed incref
  code. >_<

- The type calculus of SetL's effects on locals wasn't right. If the
  local is boxed before SetL, it'll be boxed after, regardless of what's
  on the RHS.

Reviewed By: @jdelong

Differential Revision: D1036579
2013-11-01 09:16:08 -07:00
Eugene Letuchy 905e758514 parity: update Slim framework to latest release
Minor version 2.3.5 vs 2.3.1; with a pull of the commit
 listed in run.php, it will have no errors.

Reviewed By: @ptarjan

Differential Revision: D1036922
2013-11-01 09:16:04 -07:00
Joel Marcey 7b948ad8ea Run each test from each framework individually.
This diff begins to allow indivdual tests per framework to be run in separate processes. Now we won't stop on fatals and we should be able to get a nice percentage number for all frameworks.

There is a "too many threads" spawned issue right now that needs fixing (deadlocking occurs as I create too many at this point). But let's start the review process.

Also did a fairly sizeable refactoring too.

Reviewed By: @ptarjan

Differential Revision: D1035690
2013-11-01 09:15:59 -07:00
mwilliams ace23b01ce depthOne already checks that the depth is one
thats it

Reviewed By: @edwinsmith

Differential Revision: D1035861
2013-11-01 09:15:48 -07:00
Bert Maher 8575f79d64 Translate FPushClsMethod
This adds new IR opcodes to lookup class methods from the TC
instead of interpreting.  LookupClsMethod basically does the same
thing as the interpreter; LookupClsMethodStatic is optimized for the
case where the call is in a static function.

Additionally, when the class input comes from a LdCtx we can get the
method slot at jit time and burn that into the TC.  This case is
pretty common since "LateBoundCls; FPushClsMethod" is a common
pattern.

Reviewed By: @jdelong

Differential Revision: D1035577
2013-11-01 09:15:40 -07:00
Abel Nieto a94364d310 Patch unserialize so that it handles namespaced collections
We want to be able to unserialize both Vector and HH\Vector.

Patch unserialize to that effect.

Reviewed By: @elgenie

Differential Revision: D1031058
2013-11-01 09:15:11 -07:00
David Soria Parra 497676b54f Let the HHVM debugger client/server listen on IPv6
We manually initialize the IPV6 sockaddr_in6 structure
as gethostbyname_r has problems with numeric IPv6 adresses
(http://sourceware.org/bugzilla/show_bug.cgi?id=5479). In the particular
case it fails with permission denied, while it works with the equivalent
ipv4 address.

Reviewed By: @mikemag

Differential Revision: D1030284
2013-11-01 09:15:06 -07:00
Jordan DeLong 77daeaa7c1 Remove two unused hashtables from ExecutionContext
Reviewed By: @dariorussi

Differential Revision: D1035098
2013-11-01 09:15:02 -07:00
Jordan DeLong 9944d09edc Make collection mask bits a little clearer
Easier to see how many bits are left in o_attributes.

Reviewed By: @edwinsmith

Differential Revision: D1035048
2013-11-01 09:14:57 -07:00
Javier Eguiluz 89aa1e64b5 Fix doc typos
Fix doc typos

Closes #1231

Reviewed By: @JoelMarcey

Differential Revision: D1035977

Pulled By: @scannell
2013-11-01 09:14:48 -07:00
Owen Yamauchi 43dabf533d Fix bug: "unbox()", not "innerType()"
I failed to appreciate the difference between the two (unbox works on
types that aren't necessarily boxed) in my last diff.

Reviewed By: @edwinsmith

Differential Revision: D1035871
2013-11-01 09:14:44 -07:00
Sean Cannella 4d80a542d1 Fix build break on aarch64
On aarch64, don't break the default build.

Reviewed By: @oyamauchi

Differential Revision: D1034887
2013-11-01 09:14:39 -07:00
Jordan DeLong 76ea945b56 Translate FPushCuf in more contexts; add fast paths
Adds fast paths in native helper functions for some common
cases for FPushCuf; bails to the full vm_decode_function logic if
things are less than simple.

I also tried a fast path for strings with class names ("Foo::bar"),
which made those calls about 2x faster in micro-benchmarks, at the
expense of making "self::foo" about 3x slower.  It was in the noise on
perflab, and also required differences in autoload order, so I'm
leaving that one out for now.

Reviewed By: @bertmaher

Differential Revision: D1032035
2013-11-01 09:14:34 -07:00
naresh 101c45fa9a Support systems without BFD_DECOMPRESS flag
Support systems without BFD_DECOMPRESS flag

Closes #1102
Closes #1225

Reviewed By: @markw65

Differential Revision: D1034235

Pulled By: @scannell
2013-11-01 09:14:10 -07:00
James Bornholt 38619fc4bf Fix handling of non-int/array flags to filter_var
HHVM treats all non-int flags as arrays, but Zend treats all
non-array flags as ints, so HHVM handles e.g. string flags
incorrectly. Reverse the logic to match Zend.

Closes #1226

Reviewed By: @alexmalyshev

Differential Revision: D1034218

Pulled By: @scannell
2013-11-01 09:14:01 -07:00
Rachel Kroll 65c7f03d4b Remove old cache code from hphp
Remove the old code (with a few lingering stubs to be cleaned up in a future change)

continuous build seems to be expecting bad strings in unrelated code

Reviewed By: bmaurer

Differential Revision: D1030191
2013-11-01 09:13:50 -07:00
aravind 6ce6334141 Add refcount validation pass
This adds a refcount validation pass. The pass creates an
approximation of a map from SSATmps to refcount-deltas for
each exit block. The validation consists of verifying that the
deltas are same before and after refcount optimizations.
This is run only in debug mode or under the runtime
flag Eval.HHIRValidateRefcount.

Reviewed By: @ottoni

Differential Revision: D1022219
2013-11-01 09:13:45 -07:00
Owen Yamauchi b638f9c0bd Be less aggressive in dropping types on OverrideLoc
The assert in the minstr translator was failing in
test/quick/poly-torture.php. The setup is: there's a CGetM whose base is
boxed, and before the CGetM there's an InterpOne that causes us to drop
all knowledge of refs' inner types in the frame. (This happens in x64
mode too if I force IncDecL to be interped.)

We can actually drop the inner types to InitCell instead of just Cell --
you can't have a reference to uninit. Then we can slightly weaken the
assert in the minstr translator, and it will pass. Weakening the assert
is justifiable; the codegen for LdRef knows that it shouldn't bother
emitting a typecheck if the box's inner type is InitCell.

Reviewed By: @swtaarrs

Differential Revision: D1033158
2013-11-01 09:13:40 -07:00
mwilliams c81f911e0a Refactor some more countable code
This is intended to be code cleanup, with no real change in
functionality, but should make the sign-bit-as-static-indicator
diff much smaller, and easier to reason about.

Reviewed By: @andralex

Differential Revision: D1030409
2013-11-01 09:13:30 -07:00
Edwin Smith b57f4c969d Extended Linear Scan Register Allocator
Based on Christian Wimmer's 2010 paper.

Reviewed By: @jdelong

Differential Revision: D997084
2013-11-01 09:13:16 -07:00
Edwin Smith 062178e270 Fix Shuffle bugs with unused dests and constants copied to DefLabel
Shuffle didn't handle two corner cases correctly:
1. unused destinations.  These could/should be eliminated upstream
but there's nothing incorrect about them, we can just ignore those
copies.
2. a DefConst feeding into a DefLabel needing 2 registers; We already
handled DefConst, but not when the destination doesn't have a known
type.  e.g. merge(1,"foobar") => {Int|StaticStr}, which needs 2
registers.

Reviewed By: @dariorussi

Differential Revision: D1032504
2013-11-01 09:13:11 -07:00
aravind 1b9dd05bc9 Don't increment result of StLoc unless it is pushed
StLoc was producing an incref on its result even if the result
was not pushed on stack (consumed).

Reviewed By: @ottoni

Differential Revision: D1032861
2013-11-01 09:13:05 -07:00
Guilherme Ottoni 2cf4ab129e Cleanup selectTraceletLegacy
It was taking a full RegionContext when it only needs the spOffset.

Reviewed By: aravind

Differential Revision: D1032271
2013-11-01 09:13:00 -07:00
Sara Golemon 6fca9198e5 Use gcc-4.8 on travis for faster builds 2013-10-30 13:11:46 -07:00
Owen Yamauchi d5db0d8b98 Fix some bugs with fb_setprofile in ARM mode
- Have separate stubs for the three return helpers. They don't need to
  be implemented yet, but they all need to have distinct addresses
  because we compare against retInlHelper directly to determine whether
  to run function-exit hooks.

- This exposed a bug in cgGuardRefs, where the "is logical immediate"
  assert was firing. This time I actually invested real time into
  understanding what the hell's going on there and rewrote the thing
  properly. (There are still some improvements to be had: most notably,
  when the mask is a single bit, we can use Tst instead of And-Cmp.)

- Fixups done on faked-up ARs in the simulator's catch block were
  succeeding, but not ones done from VMRegAnchors. The underlying cause
  is that the VM stack is not participating in the native frame pointer
  chain, because we're not using native call instructions to get into or
  out of the TC. I added logic to FixupMap that looks at the stack of
  simulators stored in ExecutionContext, and reads their registers to
  look for the place to apply the fixup.

Reviewed By: @edwinsmith

Differential Revision: D1032483
2013-10-29 17:05:58 -07:00
Owen Yamauchi a2704716f4 Add sync points in ARM code; sync registers on exceptions from simulated code
Fixups for simulated calls to C++ were basically not working at all.
This fixes a couple of test failures. There are still some failures left
that are failing with a null AR* in fixupWork, which I'm researching
separately.

To add the pseudo-unwind personality to the simulator, I made a
mechanism to provide an "exception hook". Eventually we'll probably want
it to return a flag indicating whether or not to re-throw, but that's
not necessary yet. I made it a hook instead of implementing the logic
right in the catch block to avoid having vixl depend on libruntime.

Reviewed By: @edwinsmith

Differential Revision: D1031833
2013-10-29 17:05:47 -07:00
Daniel Sloof 729ab7d033 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-29 17:05:38 -07:00
Michal Gregorczyk 602f634292 Record time spent in usleep function.
Added 4 counters to Transport to track how long thread sleeps in various sleep functions
when serving a request. I exported the request through hphp_get_timers.

Reviewed By: @mikemag

Differential Revision: D1021385
2013-10-29 17:05:33 -07:00
Brett Simmers f6493ff67a 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-29 15:17:44 -07:00
Abel Nieto 9306c9df11 Add stuff missing from the FrozenVector API
Vector had a bunch of methods that were not available in FrozenVector.
Add the ones that make sense given that FV is immutable (e.g. we can't sort it).

Reviewed By: @paroski

Differential Revision: D1014907
2013-10-29 15:17:44 -07:00
Alex Malyshev 9cc9ce7a52 Implement glob:// stream
Adds GlobStreamWrapper, a subclass of Stream::Wrapper.

Reviewed By: @ptarjan

Differential Revision: D1028484
2013-10-29 15:17:44 -07:00
Joel Marcey 6a7071c1c2 Stub out ZipArchive using HNI
ThinkUp fataled on the lack of a ZipArchive class. Well, here it is. Stubbed out.

Reviewed By: @ptarjan

Differential Revision: D1025542
2013-10-29 15:17:43 -07:00
Paul Tarjan bf57855cc8 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-29 15:17:43 -07:00
Paul Tarjan c06684768f 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-29 15:17:43 -07:00
mwilliams 482852ef22 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-29 15:17:43 -07:00
Owen Yamauchi d87087977d Implement ARM closure prologues
I left this unimplemented in my initial prologues diff, just out of
laziness. Time to actually get it done.

This diff contains anecdotal validation for my decision to fork code-gen
instead of trying to put the ARM assembler behind the X64Assembler
interface. Note the AttrStatic part in the closure prologue
implementation -- the x64 version uses a weird quirk of the shrq
instruction that puts the former LSB in the carry flag. Trying to
emulate that in terms of ARM instructions seems pretty foolish.

Reviewed By: @markw65

Differential Revision: D1025972
2013-10-29 15:17:42 -07:00
Eugene Letuchy c0443bc8eb tools: some pretty printing changes in gdb helper
* __doc__ for the module
 * Make RECOGNIZE regex part of the process of defining a pretty-printer
 * remove ##lambda x: bar(x)##

Reviewed By: @ptarjan

Differential Revision: D975674
2013-10-29 15:17:42 -07:00
Paul Tarjan ae4982f60b Introduce ProxyArray
Mutation operations can reseat the original array. In zend land, this isn't the case so we need a wrapper for the original array which will change its internal pointer during any reseating operation.

I verified that every method was implemented in this by removing the inheritance and making sure there were no unknown methods in the big table.

Reviewed By: @jdelong

Differential Revision: D1009352
2013-10-29 15:17:42 -07:00
Paul Tarjan acc91affa7 fix varargs for mongo
`sysdoc.php` didn't handle the varargs annotation

Reviewed By: @aryx

Differential Revision: D1030692
2013-10-29 15:17:41 -07:00
Eugene Letuchy 56ba16934f parity: correctly prevent 'self' and 'parent' user classes
Verily, case sensitive and insensitive comparisons are not
 the same. Zend knows this too: http://codepad.viper-7.com/YmAmQk

Reviewed By: @jdelong

Differential Revision: D1031067
2013-10-29 15:17:41 -07:00
aravind 40d4c00e6e Allow multiple exit blocks for Jump optimization
The main trace can have multiple exit blocks. Allow jump
optimization to work with such traces.

Reviewed By: @jdelong

Differential Revision: D1031384
2013-10-29 15:17:41 -07:00
Jordan DeLong 8d889ea18a Initial HHBBC commit (prototype of bytecode optimizer)
Reviewed By: @swtaarrs

Differential Revision: D1025662
2013-10-29 15:17:36 -07:00
Jordan DeLong 74e6f0a1a2 Pass HardTypeHints=0 for slow/invalid_argument/1383.php in RepoAuthoritative
This is another test that recovers from VerifyParamType,
which we don't handle correctly in RepoAuthoritative mode (by design).
Modify it so it will SEGV without the correct flags, and then pass
them.

Reviewed By: @markw65

Differential Revision: D1019278
2013-10-29 12:02:39 -07:00
Jordan DeLong bb8eb52d68 Add a NopDefCls opcode, for use with always hoistable classes
Every PreClass structure contains an Offset pointing usually
into the psuedo-main, to the DefCls for that PreClass.  For closures
it points to the opcode after the CreateCl (perhaps unintentionally?).
If a merge-only unit fails to define a class, it "fakes" like it was
running the psuedo-main, and sets PC to this offset before raising the
error.  Right now, a Nop is placed in the bytecode for this.  This
changes things to have a new instruction for this case, so that static
analysis of the bytecode can see why the Nop was there.

Reviewed By: @edwinsmith

Differential Revision: D1029696
2013-10-29 12:02:35 -07:00
Jordan DeLong f9a715189d Add support for more assert types opcodes; fix assert stack offsets
Option types, static string and static array, and specific
class types.  And AssertTStk was not correctly computing the Location.

Reviewed By: @swtaarrs

Differential Revision: D1029072
2013-10-29 12:02:31 -07:00
Jordan DeLong 4484f29d9f Another bytecode spec tweak for WFooIter instructions
I messed up how they treat %4 in the last update.

Reviewed By: @dariorussi

Differential Revision: D1029665
2013-10-29 12:02:27 -07:00
Jordan DeLong 048c37f4a5 Add a BreakTrackHint hhbc instruction
HHBBC sometimes infers that functions return Bottom
(i.e. infinite loop or always throw).  In this case, after the FCall,
I want to insert a String "static analysis error"; Fatal sequence, but
that sequence ends up included in the Tracelet that does the FCall.
One way to break it is to have the analyze pass / region selectors
recognize this pattern, but it seems that this might come up in other
contexts where ahead-of-time analysis may have good reasons to suggest
tracelet breaks (e.g. to avoid our "double tail" problem on control
flow diamonds, or maybe StaticLoc?).

Reviewed By: @swtaarrs

Differential Revision: D1029595
2013-10-29 12:02:23 -07:00
Jordan DeLong af481f5e9b Add a PopA instruction
This aids in implementing strength reduction if you can
constant propagate to instructions taking a classref when there is a
*D form.  (E.g. AGetL; ClsCns converting to ClsCnsD, FPushClsMethod ->
FPushClsMethodD, etc.)

Reviewed By: @bertmaher

Differential Revision: D1029405
2013-10-29 12:02:19 -07:00
Jordan DeLong 11c74ec9eb 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-29 12:02:14 -07:00
Jordan DeLong 46aac2e534 Some tweaks to continuation opcodes in bytecode.specification
We put the top of stacks toward the right in the spec.  Also,
make it a little clearer that CreateCont and CreateAsync unset locals
on the current frame.

Reviewed By: @edwinsmith

Differential Revision: D1029381
2013-10-29 12:02:10 -07:00
Jordan DeLong e3727fe306 Fix bytecode spec for DecodeCufIter
It claims it pushes a bool, but it doesn't.

Reviewed By: @edwinsmith

Differential Revision: D1029315
2013-10-29 12:02:06 -07:00
Jordan DeLong 6afcba1044 Various runtime changes related to hhbbc
Mostly exposing some fields on the FooEmitters, consts, and
other small things like that.  This is split off in an attempt to make
the code review a little easier.

Reviewed By: @markw65

Differential Revision: D1025651
2013-10-29 12:02:02 -07:00
Jordan DeLong a43878fbc5 Encode NewArray capacity hints in the bytecode, with a NewArrayReserve op
This makes it easy to keep it around during the
bytecode-to-bytecode thing.

Reviewed By: @edwinsmith

Differential Revision: D1025556
2013-10-29 12:01:58 -07:00
Jordan DeLong a9b11650cb Relax invariant about empty eval stack at starts of try blocks
I don't think anything in the system actually requires this,
so we might as well not have the rule.

Reviewed By: @edwinsmith

Differential Revision: D1025601
2013-10-29 12:01:54 -07:00
Jordan DeLong 33e71c9c57 Remove MetaInfo::Kind::NopOut
Unused after D1025494

Reviewed By: @edwinsmith

Differential Revision: D1025500
2013-10-29 12:01:50 -07:00
Jordan DeLong 5f875aac6c Add various stack-flavor-only Nop opcodes; use them instead of MetaInfo
These instructions do nothing.  They match up for the cases
that we currently use metadata to nop things out, except FPassC
(because FPassC is already always a no op).  I'll remove
MetaInfo::NopOut in a separate diff on top of this to perflab it
separately.

Reviewed By: @edwinsmith

Differential Revision: D1025494
2013-10-29 12:01:45 -07:00
Alok Menghrajani f82d212f0c Remove blacklisted Xhp type
We no longer need this special case.

Reviewed By: @jdelong

Differential Revision: D1029228
2013-10-29 12:01:41 -07:00
James Bornholt cdfd08ee38 Zend parity with file() for blank files
file() shouldn't return null for a blank file. Do what Zend
 does, return an empty array.

CLoses #1216

Reviewed By: @JoelMarcey

Differential Revision: D1030231

Pulled By: @scannell
2013-10-29 12:01:37 -07:00
Sean Cannella aa92991929 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-29 12:01:33 -07:00
Bert Maher 13d98bda87 Disable SQLite memory stats to avoid locking during shutdown
Since bmaurer noticed that we spend a lot of time locking on
memory stats during webserver shutdown, and we don't do anything with
these stats anyways, let's just turn them off.

Reviewed By: bmaurer

Differential Revision: D1030301
2013-10-29 12:01:29 -07:00
Eugene Letuchy c823ab96c4 parse error for 'abstract async' ...
... because it's a meaningless syntax

Reviewed By: @paroski

Differential Revision: D1016954
2013-10-29 12:01:20 -07:00
Paul Tarjan e35c83763d 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-29 12:00:50 -07:00
Bert Maher 641a0ed1cc Fix type_profiler test
The test output depended on the sort order of equally-likely
types; we don't care about their order, but we do care about frequency
ordering, so bias the output towards integer.

Reviewed By: @scannell

Differential Revision: D1030488
2013-10-29 12:00:45 -07:00
Owen Yamauchi 5c2fb806cc Implement ARM::emitCallArrayPrologue
The x64 version of this distinguishes the case where dvs.size() == 1
because then it can use a compare with mem and immediate operands. ARM
can't do that.

Reviewed By: @edwinsmith

Differential Revision: D1028069
2013-10-29 12:00:12 -07:00
Owen Yamauchi 34dcd32cd3 Fix build breaks in various configurations
Apparently #error isn't the best thing. This fixes a couple build
blockers: building vixl natively on ARM, and building in non-fast-TLS
mode.

Reviewed By: @scannell

Differential Revision: D1029917
2013-10-29 12:00:07 -07:00
Edwin Smith f869b1e304 Rename RegisterInfo to PhysLoc
RegisterInfo either represents registers or spill locations for
an SSATmp; Looking at the way we use it, the name PhysLoc makes
more sense.

Reviewed By: @ottoni

Differential Revision: D1025818
2013-10-28 11:28:48 -07:00
Edwin Smith fbb70fa6f9 Introduce Shuffle instruction
Linear scan inserts Shuffle to resolve copies of Jmp instructions,
removed shuffle code from cgJmp.

Reviewed By: @swtaarrs

Differential Revision: D1023716
2013-10-28 11:28:42 -07:00
Edwin Smith d12929d7c2 Rename code-gen.cpp/h to code-gen-x64.cpp/h
Reviewed By: @oyamauchi

Differential Revision: D1027811
2013-10-28 11:01:40 -07:00
Edwin Smith 52f9a1f241 Use <= instead of subtypeOf in a bunch of JIT code
This is mechanical and I think it improves the code.

Reviewed By: @swtaarrs

Differential Revision: D1026129
2013-10-28 11:01:35 -07:00
Drew Paroski 6464d329dc Make array_intersect and array_intersect_key work with collections
Rewrote the algorithms for array_intersect() and array_intersect_key() to
work with collections and to achieve better performance (particularly for
array_intersect()).

Reviewed By: @dariorussi

Differential Revision: D1025142
2013-10-28 11:01:27 -07:00
Herman Venter a3101e6d7f 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-28 11:01:23 -07:00
Max Wang b6785d8a5d Implement SleepWaitHandle
Allows us to sleep asynchronously.

Reviewed By: @jano

Differential Revision: D984340
2013-10-28 11:01:14 -07:00
Joel Marcey a5363d8e21 Add an --allexcept option and fix some bugs
Add an --allexcept option that allows us to run all tests but those listed.

Fix a weird bug that happens with an HipHop warning occurs on the same line as a status. Had to fix the regex for that.

A few other fixes

Next up:
  Each test of each framework in own process
  Create per framework shell script to run only those tests that had a different status than expected

Reviewed By: @ptarjan

Differential Revision: D1028292
2013-10-28 11:01:05 -07:00
mwilliams 6258f03127 Fix a race in retranslateOpt
retranslateOpt called retranslate, which could end up
returning nullptr if another thread got the source-key lock, and
then got blocked on the write lease.

Call translate instead, and don't generate optimized translations
if the debugger is attached.

Reviewed By: @ottoni

Differential Revision: D1027892
2013-10-28 11:00:53 -07:00
Bert Maher efbb366885 Integrate into hphpd info command
Modified info command in debugger to display type information for a
specified function

Reviewed By: @hermanventer

Differential Revision: D887484
2013-10-28 11:00:48 -07:00
Mike Magruder a4492a4fc1 Revert "Use a separate field to keep track of allocations for the purpose of out of memory checking."
: This reverts commit 93009b15c5c09549425a264dc17d24cff6cb1e14.

Conflicts:
	hphp/NEWS

Reviewed By: @hermanventer
2013-10-28 11:00:44 -07:00
Abel Nieto ede2e5c30a Change the return type of map() et al
map(), filter() and their family members should return FVs, instead of vectors.

Reviewed By: @paroski

Differential Revision: D1022281
2013-10-28 11:00:40 -07:00
Owen Yamauchi 677a59c594 Remove 'using namespace JIT::X64' from tx64; implement fallback interp
Removing the using-directive exposed most of the remaining bits of
x64-specificness in tx64. I just added explicit namespace qualification
to most of them and will deal with them properly later. (I actually find
it kind of suspect that we haven't hit problems with, for example,
bindJmpccFirst yet.)

The one place where I made actual changes is in the code that handles
emitting a fallback request to interp in the event of total codegen
failure for a tracelet. Previously it was handy to keep this
unimplemented (I've been testing with an assert(false) in the
X64Assembler ctor) because it exposed places where we were getting
spurious failures because not enough IR opcodes were implemented. The
remaining places where we're hitting this failure mode are legitimate:
polymorphic tracelet explosion and running out of spill space.

Reviewed By: @ottoni

Differential Revision: D1027996
2013-10-28 11:00:35 -07:00
Sean Cannella f4ef9cae24 Implement missing forward compat constants
Implement unused FILE_BINARY and FILE_TEXT because PHP does
even though they have no effect in PHP 5.

Closes #1215

Reviewed By: @JoelMarcey

Differential Revision: D1027907
2013-10-28 11:00:30 -07:00
Naresh 62c0cd0052 Implement PhpFileExtensions runtime option
Implement file extensions set that should be treated like PHP
files in the webserver

Closes #1207

Reviewed By: @markw65

Differential Revision: D1021819

Pulled By: @scannell
2013-10-28 11:00:25 -07:00
Sara Golemon fbd9dd7258 Don't build folly/experimental/exception_tracer/StackTrace.c
Closes #1219
2013-10-28 10:58:52 -07:00
Sara Golemon 90d08a2b8f Kill bin/ directory
Move generated systemlib.php to hphp/system/
Let other intermediates live in their CMakeFiles dirs
2013-10-25 15:31:28 -07:00
Sara Golemon 7dacd36a25 Clean up ext_hhvm CMakeLists.txt 2013-10-25 15:16:42 -07:00
Sara Golemon 8a15eeb271 Minor refactor of CMake files
Move hphp_runtime_static build steps into hphp/runtime
Save main hphp/CMakeLists.txt to be a meta makefile
2013-10-25 14:56:26 -07:00
Sara Golemon 77f7c80733 Pick up new folly changes 2013-10-25 14:01:39 -07:00
Owen Yamauchi 9435d5cb5f Implement debugger guards for ARM
All the debugger tests were failing because of this.

The Tricky Topic of the Day introduced in this diff is ARM code's
interaction with thread-local storage. ARM has its own way of getting a
pointer to thread-local storage (already implemented in tlsBase()) but I
don't know exactly how it works -- i.e. whether it works the same way as
on x64, where the system register points to an area with a bunch of
pointers to thread-local objects. ARM certainly doesn't have
segmentation the way x64 does.

Rather than figure all that out and implement corresponding support in
vixl, I've elected to just call into C++ to get the TLS base. This is
going to be one area where simulated-ARM mode diverges significantly
from native-ARM mode, but we'll cross that bridge when we come to it.

Reviewed By: @jdelong

Differential Revision: D1023960
2013-10-25 12:03:42 -07:00
mwilliams 93842ddea9 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-25 12:03:34 -07:00
Jan Oravec 1e752dda0d Remove unused childOfYield and hphp_continuation_done()
childOfYield flag and hphp_continuation_done internal method are no
longer used. Remove them.

Reviewed By: alexsuhan

Differential Revision: D1016610
2013-10-25 12:03:30 -07:00
Joel Marcey 0de11da8e7 fix stream_select error
I am a clown.

Reviewed By: @ptarjan

Differential Revision: D1027352
2013-10-25 12:03:22 -07:00
Joel Marcey 40073897e8 Fix the timeout process in the oss framework test script
The timeout was broken, as in it didn't work. Take a new approach. Timeout per individual test in an individual framework instead.

Default is allow 60 seconds per test.

And some other fixes too.

Reviewed By: @ptarjan

Differential Revision: D1027221
2013-10-25 12:03:18 -07:00
Eugene Letuchy 1990ff3bd4 create a Class creation time hook
... for the purpose of adding trait-based methods to a class at PreClass-to-Class conversion time.

Reviewed By: @jdelong

Differential Revision: D1023552
2013-10-25 12:03:09 -07:00
Alex Malyshev 6b68831b2f SQLite3::escapestring should be static
We had it as an instance method.

Fixes a fatal in Joomla

Reviewed By: @scannell

Differential Revision: D1026742
2013-10-25 12:03:05 -07:00
Max Wang 878b1dc4f0 Refactor SessionScopedWaitHandle from ETEWH
Generic wait handle for async executions which are not bound by context
but rather have session scope.  Used for upcoming SleepWaitHandle.

Reviewed By: @jano

Differential Revision: D1018708
2013-10-25 12:03:00 -07:00
aravind 0dfc7771c1 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-25 12:02:56 -07:00
Alex Malyshev 0be5f85a51 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-25 12:02:52 -07:00
Jan Oravec 2782370d68 Process ready wait handles in LIFO rather than FIFO order
After eager execution, the queue of ready ContinuationWaitHandles may
contain only unblocked handles. Process the most recently unblocked first
to improve cache locality.

Reviewed By: alexsuhan

Differential Revision: D1016230
2013-10-25 12:02:47 -07:00
Paul Tarjan 5896ab5879 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-25 12:02:43 -07:00
Edwin Smith 39d72574d4 Tidy up the API to postorderWalk()
We always call it with the full # of blocks and the unit's
entry point, so just pass the unit.

Reviewed By: @jdelong

Differential Revision: D1026189
2013-10-25 12:02:35 -07:00
mwilliams 6ecedd940e 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-25 12:02:26 -07:00
Max Wang 5fb8233ee2 Allow ETE receiveSome() to timeout, as receiveSomeUntil()
We want to be able to timeout waiting for external thread event
completion in order to order correctly with async sleeps.

Reviewed By: @jano

Differential Revision: D1018706
2013-10-25 12:02:21 -07:00
Joel Marcey 348911acfb Simplify the content of the test script expect files
The expect files were containing a bit too much infomration. Now they just contain name of test and status. No other data.

Also increased the timeout (mostly because of the time for pear) and tried to text align the csv output as best I could.

Some minor other changes too

@ptarjan: You should run the graph script with --csv and --csvheader ... modify the script to handle the header that comes each time we append.

Reviewed By: @ptarjan

Differential Revision: D1025044
2013-10-25 12:00:54 -07:00
Sean Cannella 8fe484da0e 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-25 11:57:56 -07:00
Abel Nieto da31dcca9d Support (de)serialization
FrozenVector now supports serialize() and unserialize().

Additionally, as a result of the above, var_dump(some_frozen_vector)
now gives a more meaningful output.

Reviewed By: @paroski

Differential Revision: D1013734
2013-10-25 11:57:51 -07:00
Abel Nieto fb61a37771 Make the JIT aware of traits implementing interfaces
Correctly populate the instanceBits of each class so that "fast path"
taken by the JIT correctly supports traits implementing interfaces.

Reviewed By: @swtaarrs

Differential Revision: D1023165
2013-10-25 11:57:47 -07:00
Joel Marcey 89827a6513 Just some minor fixes to the code generator for HNI
After stubbing out ZipArchive, there were a few issues that caused complilation problems. This fixes those.

- Add a string argument to NotImplementedException
- Change CStrRef to const String&
- I think "null" should be "void" in the typemap; otherwise you get "static null HHVM_METHOD" type functions.

Reviewed By: @sgolemon

Differential Revision: D1025577
2013-10-25 11:57:42 -07:00
Sara Golemon 2ecabd236d Switch folly to using a submodule instead of a fork.
To sync the folly submodule the first time, you'll need
to issue:

git submodule init
git submodule update

From then on, you'll also want to make sure folly is up to
date by issuing `git submodule update` after a `git pull`.
2013-10-25 11:45:56 -07:00
Sara Golemon 3fd7ec17f7 Skip mongo tests when ext not built in 2013-10-24 13:54:56 -07:00
javer 920046e2c2 Preserve class property DocComment for reflection
This allows to use annotations in Doctrine 2 ORM Entities.

Fixes 225 unit tests in doctrine/doctrine2.
Fixes 118 unit tests in doctrine/annotations (100% passes now).

Closes #1199

Reviewed By: @paroski

Differential Revision: D1019739

Pulled By: @scannell
2013-10-24 11:49:39 -07:00
Edwin Smith 0afb900ab3 Per-instruction register map
Change RegAllocInfo from a 1D SSATmp->RegisterInfo map to a
2D IRInstruction,SSATmp->RegisterInfo map.  This lets the register
allocator assign a different register or spill slot to a single
SSATmp at different locations during its lifetime.

Reviewed By: @ottoni

Differential Revision: D1021754
2013-10-24 11:49:39 -07:00
Eugene Letuchy 71d75a0144 make traits tests independent of the contents of systemlib
... it's not germane to the purpose of the tests: nor is it
 sustainable to continue to add/remove the names of system traits from
 these tests. A possible alternative is to pass a flag to
 get_declared_classes|traits to exclude systemlib builtins.

Reviewed By: @paroski

Differential Revision: D1023627
2013-10-24 11:49:39 -07:00
Jordan DeLong f97767ee50 Change magic number in memory-manager debug mode to be more 1337
The old magic number was pretty shamefully bad.  It's
definitely no 0xC01O55A1B0B51ED5, but maybe this is a little better
than what it was ...

Reviewed By: @edwinsmith

Differential Revision: D1019412
Differential Revision: D1025644
2013-10-24 11:49:28 -07:00
Jordan DeLong 5ce77ede53 Don't allow certain AssertType types in the JIT for now
The JIT will crash in some situations with these.  We can end
up going to cgAssertType with a constant src, which will break when it
didn't have registers.

Reviewed By: @swtaarrs

Differential Revision: D1019432
2013-10-24 08:07:12 -07:00
Jordan DeLong 960f3e2194 Make AssertT* instructions actually affect tracelet length and guards
Reviewed By: @swtaarrs

Differential Revision: D1019431
2013-10-24 08:07:12 -07:00
Jordan DeLong d952cf1e4f Reformat FileScope::analyzeIncludesHelper
I was trying to understand what this function does, and this
made it a bit easier for me to follow the logic (less nesting).

Reviewed By: @andralex

Differential Revision: D1018846
2013-10-24 08:07:12 -07:00
bsimmers 35cc0c5d54 Don't look at NormalizedInstruction's fields to translate FPushClsMethodF
The information is available in the IR.

Reviewed By: @jdelong

Differential Revision: D1020934
2013-10-24 08:07:11 -07:00
bsimmers 0d316a5b7e Stop using Classes from NormalizedInstruction in emitFPushObjMethodD
This information is available in the IR so let's get it from there
instead of NormalizedInstruction. This is part of my crusade to minimize
IRTranslator's role and eliminate NormalizedInstruction.

Reviewed By: @ottoni

Differential Revision: D1020925
2013-10-24 08:07:11 -07:00
bsimmers 23c3e83f11 Move most of FPushCuf's work from IRTranslator to HhbcTranslator
This kind of logic doesn't belong in IRTranslator, especially since
it's a thin layer we'd like to eventually get rid of.

Reviewed By: @oyamauchi

Differential Revision: D1020911
2013-10-24 08:07:11 -07:00
bsimmers 4c36e0af6a Stop using class names from NormalizedInstruction in emitAGet*
If the names are really constant, they should be available to
HhbcTranslator. If there are any cases where they're not available, we should
make them available.

Reviewed By: @jdelong

Differential Revision: D1020897
2013-10-24 08:07:11 -07:00
bsimmers f6e0bc47c2 Clean up class property and global setting/getting code
This code was quite old and was using predicted types and strings
passed in from fields on NormalizedInstruction, which will be going away
soon. It's been changed to just use the information we already have available
in m_evalStack and rely on the optimizations/prediction support we have now. I
also fixed a bug where the name string wasn't being consumed on every path by
reworking who's responsible for destroying it.

Reviewed By: @jdelong

Differential Revision: D1020885
2013-10-24 08:07:10 -07:00
bsimmers b11dbab7bb Clean up Assert(Type|Loc|Stk), add filterAssertType
filterAssertType is used by some upcoming code to handle things like
assserting {InitNull|Obj<C>} when the known type is Obj. I also cleaned up how
we handle invalid types from static analysis. We used to replace the assert
instruction with a Fatal, but we can still end up generating bogus IR if we
continue translating. The best thing to do (for now) is to punt on the whole
trace, since there's no clear way to create well-formed IR for the whole thing.

Reviewed By: @jdelong

Differential Revision: D1020613
2013-10-24 08:07:10 -07:00
bsimmers d70e4828ea Add new dest types for LdRef and This, add support for weak type constraints
LdRef now removes any specialization from what we think is in the
inner type, to avoid having to guard on it again. This produces a value
specialized with the current context class. Weak type constraints go through
the process of finding the appropriate guard to constrain but don't actually
constrain the guard. They can be used to determine if we can use a specialized
type without having to add any additional guards, which I'll need to do in an
upcoming diff.

Reviewed By: @ottoni

Differential Revision: D1020843
2013-10-24 08:07:10 -07:00
bsimmers 619dfe69ea Don't read NormalizedInstruction's inputs in IRTranslator
I'm planning on eliminating the inputs vector soon. Reading types from
it (instead of HhbcTranslator) can bypass guard relaxation, and the information
is all available elsewhere. This diff just includes the straightforward cases;
the more invasive bytecodes will come in separate diffs.

Reviewed By: @ottoni

Differential Revision: D965348
2013-10-24 08:07:09 -07:00
Bert Maher 34eeb251e5 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 08:07:09 -07:00
Guilherme Ottoni 9fba6f4f73 Regionize and retranslate each function at once
This diff changes how region translation operates, with the goal of
improving code locality.  Instead of triggering retranslation at a
translation granularity, this diff changes things so that only
translations corresponding to the function-body entry trigger
retranslations.  The other translations still keep their profile
counters, which are used to guide region formation.

When an optimized retranslation is triggered for a function, a series
of regions is created for this function.  These regions ensure that
all profiling translations for this function (and control flow arcs
connecting them) are covered by the regions created.  The regions are
then translated consecutively in the TC, following an order that tries
to improve the locality of the generated code.

After a function has been regionized, any retranslation that is
triggered by new live types uses the tracelet JIT.

Reviewed By: @swtaarrs

Differential Revision: D1017506
2013-10-24 08:07:09 -07:00
Sean Cannella 07e72438f2 Re-implement GenerateDocComments
GenerateDocComments had inadvertently become a no-op. Restore
it.

Reviewed By: @markw65

Differential Revision: D1023934
2013-10-24 08:07:08 -07:00
Sean Cannella 453195bb1f Remove dead hphpc options
Remove hphpc options that are no longer used

Reviewed By: @markw65

Differential Revision: D1023862
2013-10-24 08:07:08 -07:00
Kristaps Kaupe 223bdd7523 Native.h macro typo
Fix macro typo

Reviewed By: @JoelMarcey

Differential Revision: D1023850

Pulled By: @scannell
2013-10-24 08:07:08 -07:00
Paul Tarjan 9d1d782cf0 re-import zend headers
Had I been smarter when I started this project, I would have done this from the begining. It used to be a hodgepodge of some implementation in headers and others in .cpp. When I would import a new extension I had to fight importing all the new macros and function signatures, putting them in their right place or else I will get compile errors.

So, I spent today cleaning up this story. Now all headers are original Zend (codemodded with tabs to spaces) with any changes I needed to make wrapped in a `#ifdef HHVM`. That way if I ever want to re-import I can slice it and insert it easily. It also has the nice property that the old code is right there so you can compare at the glance what I am doing and what they are doing.

I updated the README to explain the file structure.

I talked to @jdelong and @markw65 about a good long-term solution. @jdelong things we should code to the API and not share any implementation, @markw65 prefers compile errors  but said link errors would be ok. He just doesn't think I should pull in all the implementations and force run-time errors since those would be hard to debug. I think having their `.h` files and our own `.cpp` is a good compromize for now.

Reviewed By: @paroski

Differential Revision: D983907
2013-10-24 08:07:08 -07:00
Paul Tarjan 215b2d2e2c import mongo extension
This is the biggest extension on pecl. Most of their tests depend on a server implementation which I don't really want to package into our test infra yet.

Many of the tests don't pass, but I want to get this up for review with the passing tests since i think many of the changes are good.

Reviewed By: @paroski

Differential Revision: D979397
2013-10-24 08:07:01 -07:00
Jordan DeLong f8cde99fb2 A few bytecode spec tweaks (relating to FPI, cuf iters)
It's not explicitly listed, but we can't have Catch, Fault or
DV entry offsets inside of FPI regions, so I added that.  Also update
a little bit about Cuf iters.

Reviewed By: @edwinsmith

Differential Revision: D1019493
2013-10-24 07:39:10 -07:00
Jordan DeLong 816863ff6f Make Fatal take only a single OA arg
This was a little more convenient for the bytecode
representation I'm using (it's nice but not critical that all opcodes
with subops only have a single subop).  Also hook up to assembler
while here.

Reviewed By: @alexmalyshev

Differential Revision: D1022933
2013-10-24 07:39:06 -07:00
Jordan DeLong 1e848825b7 Add an unsupported case in scalar array emission
If you don't run some of the optimization passes, sometimes
scalar arrays from UnaryOpExpression will have sub-members that are
other UnaryOpExpressions, which isn't handled here.  It looks like
getScalarValue is there for this.

Reviewed By: @edwinsmith

Differential Revision: D1017234
2013-10-24 07:38:56 -07:00
Bert Maher 0a338e7d49 Partial de-trace-ification of DCE
Some cleanup of DCE, attempting to get rid of IRTrace where
it's not needed.  A lot of DCE deals explicitly with traces so I'll
leave that for the another diff.

Reviewed By: @edwinsmith

Differential Revision: D1023480
2013-10-24 07:38:51 -07:00
Edwin Smith cdebfada6f Use hints instead of trace to order blocks in postorderWalk()
postorderWalk() chooses which successor blocks to visit based on
trace; it visits main->exit edges first, to bias towards visiting
them sooner.  (So they'll be later in reverse-postorder).
This diff uses block hints instead.  This will result in slightly
different order for if/then/else regions with an Unlikely arm, that
were entirely on the same trace.  But it should be equivalent for
main->exit edges since exit blocks are all marked Unlikely.

Reviewed By: @jdelong

Differential Revision: D1022275
2013-10-24 07:38:46 -07:00
Sara Golemon e8b0e6a6ed Link against libpam if it's available
The logic looking at c-client's linkage.h file is too clever. (hah)
Just follow PHP's example and always link it when possible.

Closes #1181
2013-10-23 23:31:03 -07:00
Franck STAUFFER e69df8d6e4 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 08:24:41 -07:00
Owen Yamauchi 05dc23323c Implement unconditional jump smashing on ARM; fix lolbug
There were two problems. First, jmpTarget() wasn't recognizing jumps
properly because I was looking at the wrong instruction bits. Then,
smashing unconditional jumps wasn't implemented.

Reviewed By: @jdelong

Differential Revision: D1021956
2013-10-23 08:24:37 -07:00
Owen Yamauchi 0e34715a4a Implement function prologues in ARM
This is mainly what's holding us back in test/quick. There's a lot of
stuff going on here:

- Adding code-gen-helpers-arm.cpp. There's a practical need for this:
  we're starting to write out a lot of calls to C++ functions, which
  should be abstracted out because it happens differently depending on
  whether we're simulating ARM or running on native ARM.

- Initialize rStashedAR when starting the simulator. This was a bug.

- Change the order of pushing x29 and x30 around calls to properly mimic
  the x64 stack frame.

- Implement fcallHelperThunk.

- Templatize a couple of vixl functions to let us move pointers into
  registers without reinterpret_cast. Also fill the simulator stack with
  junk before starting up a simulator; in an early version of this diff
  we were actually reading from the stack out-of-bounds. It wasn't
  causing any bugs, but let's get out ahead of that.

Reviewed By: @jdelong

Differential Revision: D1019980
2013-10-23 08:24:33 -07:00
Igor Zinkovsky ebb082916f send all Logger output to stderr
Prior to this change, Logger::Info and Logger::Verbose were going to
stdout, which can easily break scripts.

I didn't see any Logger::Info or Logger::Verbose call sites, which assume that
their output is going to stdout.

Reviewed By: @paroski

Differential Revision: D962372
2013-10-23 08:24:28 -07:00
aravind f1b382e431 Don't trace through IncRef for SpillStack
This can cause mismatched IncRef/DecRef pairs in the IR.

Reviewed By: @swtaarrs

Differential Revision: D1022881
2013-10-23 08:24:24 -07:00
Paul Tarjan 836d7b81a3 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 08:24:20 -07:00
Drew Paroski 6b57769566 Make array_diff and array_diff_key work with collections
This diff reimplements array_diff() and array_diff_key() to be more
performant and to support collections.

The new implementation is more than 5x faster the old implementation on a
number of micro-benchmarks I tried, with some of the micro-benchmarks
showing as much as a 40x improvement.

Reviewed By: @dariorussi

Differential Revision: D1019693
2013-10-23 08:24:08 -07:00
Joel Marcey ae92abb5c6 Fix issue with composer timing out on downloading dependencies and fix deadlocking
- Fix issue with composer timing out on downloading dependencies
- Try to reduce or eliminate deadlocking by using individual repos for each framework run
- Add Mediawiki to the frameworks; Remove typo3 since the tests are running correctly
- Simplified the expect files to just have test and status
- Other modifications

I have decided I need to refactor this thing a bit. May try to parallelize it more. Probably make some classes. Etc. For example, I should add a --jit and --nojit mode, probably.

Reviewed By: @ptarjan

Differential Revision: D1022337
2013-10-23 08:21:23 -07:00
Owen Yamauchi 1274347ca3 Implement codegen for UnpackCont in ARM mode
UnpackCont is troublesome to interp-one; it doesn't even work in x64
mode. It translates to a single IR instruction, so this just implements
codegen for that.

In the process of debugging, I discovered that the stack-chasing for
UnpackCont was getting the order of its stack outputs wrong.

Reviewed By: @edwinsmith

Differential Revision: D1020297
2013-10-23 08:13:28 -07:00
Owen Yamauchi 0e2b208855 CGetL2 looks past a StackElem, not a Gen
IR translation for CGetL2 was assuming the top element on the stack was
a Gen, but it can also be a Cls. StackElem unifies these two types, and
is what we want.

Reviewed By: @swtaarrs

Differential Revision: D1022105
2013-10-23 08:13:24 -07:00
Rachel Kroll 47b8369f86 Create file cache as 0664, not 0600
Match mode for file cache relative to original code

Reviewed By: @emiraga

Differential Revision: D1022126
2013-10-23 08:13:20 -07:00
bsimmers dc1abd31c5 Revert "[hphp] make 'abstract async' syntax error only behind !(whole program)"
We're still not ready for this.

Reviewed By: @elgenie
2013-10-23 08:13:16 -07:00
Andrey Sukhachev b825e9fa88 Provide an API to store an APC key without the TTL adjustment applied.
Why do I need that?
On devservers I need to be able to store certain APC keys without them
being automatically evicted when the TTLLimit expires, i.e. to simulate
the "primed" behavior in sandboxes, which don't have apc_prime.so.
The  cost of rebuilding these keys can negatively impact the sandbox
performance.

The function name is intentionally scary do discourage the unintentional
use (which mimics the www conventions).

Reviewed By: @dariorussi

Differential Revision: D1016718
2013-10-23 08:13:11 -07:00
Bert Maher 072cb790d2 Print and toString for Blocks
These are nice to have when poking around in gdb

Reviewed By: @edwinsmith

Differential Revision: D1021633
2013-10-22 10:00:20 -07:00
Edwin Smith 59dd9c68a7 Remove Block::m_func and un-plumb it through the JIT.
I think the need for m_func has been subsumed by every instruction
having a BCMarker.  This is a mechanical change; m_func was dead.

Reviewed By: @ottoni

Differential Revision: D1019715
2013-10-22 10:00:20 -07:00
bsimmers 654c563286 Skip function exit events after side exiting in an inlined call
This is slightly less optimal than running the function enter event in
the exit trace, but it's significantly simpler and safer. I might investigate a
better solution some time in the future.

Reviewed By: @mikemag

Differential Revision: D1020793
2013-10-22 09:53:16 -07:00
Julius Kopczewski 0445bebfd7 Refactoring JobDispatcher for greater type safety
Removed a superflous template argument for the Dispatcher,
replaced void* m_opaque for typed m_context.

Reviewed By: @jdelong

Differential Revision: D988558
2013-10-22 09:53:08 -07:00
Paul Tarjan baf17e9b74 change to https://
I want to be able to run these headless, and with the `git@` urls it tries my public key first.

Reviewed By: @JoelMarcey

Differential Revision: D1020293
2013-10-22 09:53:00 -07:00
Herman Venter 733fe14815 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 09:52:56 -07:00
Matthias Eck 7cd23392b0 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 09:52:51 -07:00
Yuval Hager a1be625704 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 14:16:53 -07:00
Sean Cannella fbf30c70f5 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 14:16:49 -07:00
Sean Cannella e4c6ee2e8a Fix template explosion in TransRec::print
folly::format explodes and exceeds a sane template depth so
break up the calls.

Reviewed By: @swtaarrs

Differential Revision: D1019754
2013-10-21 14:16:45 -07:00
Bert Maher fa892e57b8 Jump opt for side-exiting jcc's
In the region compiler we can create side exits due to
user-level control flow, and we'd like the side exit to not go through
Astubs after it's been chained, if possible.  This optimization is
almost like what we already have for CheckStk and CheckLoc, but we
need it for Jcc's too.

Reviewed By: @jdelong

Differential Revision: D1019242
2013-10-21 14:16:33 -07:00
Gordon Huang 58cbeb02d5 Add two more functions to FBUnserializer API
This diff adds two functions to the FBUnserializer API, which I need to use.
1. done(), check whether the whole string is unserialized (I need it to make sure the fbobject/assoc range unserialize consumes all the input and didn't leave anything undecoded (and lost parts of the data).
2. getSerializedMap. I ran into a case that the map (structure data) comes first in the result, but the needed info (structure data fbtype) comes after that. I need to record the serialized map somewhere and then redecode the map with the fbtype.

Reviewed By: andrii

Differential Revision: D1018331
2013-10-21 14:16:29 -07:00
Sean Cannella 073579b5b4 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 14:16:24 -07:00
Anton Grbin 03567b7026 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 14:16:20 -07:00
Paul Tarjan 1632ca1184 rename HPHP_VERSION to HHVM_VERSION
People keep asking me how to verify their upgrade worked and I tell them to print this constant. Then they always ask why is it still named HPHP. Good question.

I left the old one. Maybe we can kill it in 6 months?

Reviewed By: @sgolemon

Differential Revision: D1019640
2013-10-21 14:16:00 -07:00
Sara Golemon 6dbd9c85f6 Revert temporary gcc 4.6 hacks.
I modded the OSS version of the repo last week to keep it
building on gcc 4.6.  After much discussion we're setting the
minimum version at 4.7 and rather than sync these hacks internally
we'll be reverting them from the OSS side.
2013-10-21 13:49:18 -07:00
Sara Golemon e04980ca2b Increase minimum GCC version to 4.7.0
If you absolutely can't upgrade past gcc 4.6.x,
checkout tag gcc-4.6 or follow branch HHVM-2.2
2013-10-21 13:29:28 -07:00
Paul Tarjan 5848896a92 Allow default .hdf to be compiled in to php binary
Reviewed By: @swtaarrs

Differential Revision: D1013374
2013-10-20 21:02:26 -07:00
Jordan DeLong 2f4aa50bc5 Memoize getNativeFunctionName
Makes doing IR dumps faster.  (Ideally we'd combine this with
the one for Disasm but it's probably not a big difference and this
helped for now.)

Reviewed By: @swtaarrs

Differential Revision: D1013823
2013-10-20 21:02:22 -07:00
Edwin Smith e23001357e Update terminology in ir.specification to refer to blocks as blocks.
The IR is block-based now, and labels are optional.  Updated wording.

Reviewed By: @jdelong

Differential Revision: D1019285
2013-10-20 21:02:18 -07:00
Jordan DeLong 179439a9e4 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 21:02:13 -07:00
bsimmers 6d7e68a5cc tc-print improvements and fixes
tc-print used to assume that all the bytecodes in a translation were
in the same function. This was a fine assumption, but now we have inlining so
that's often not true. TransBCMapping now holds an MD5 to identify the unit it
came from. This is then used while printing bytecodes to look in the correct
unit. I included a few other small tweaks:

- Better alignment for some output, and replace a lot of snprintf with
  folly::format
- systemlib is embedded in the tc-print binary so it can be loaded at startup
  (it's not in production repos)
- The native func and class units are generated at startup
- Function names are printed in translation summaries
- Bytecode offsets are printed in decimal instead of hex, to match conventions
  elsewhere

Reviewed By: @ottoni

Differential Revision: D1016351
2013-10-20 21:02:09 -07:00
Bert Maher 88a2da1408 Describe the global litstr table in bytecode.specification
Also spellchecked, because OCD

Reviewed By: @jdelong

Differential Revision: D1017649
2013-10-18 22:18:48 -07:00
Alex Malyshev 7ae34b0022 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-18 22:18:48 -07:00
Owen Yamauchi 4915bdf7fd Add support for emitting PC-relative loads to vixl assembler
The lower-level assembler infra is there, but this addressing mode
wasn't exposed in the public-facing API. This will allow us to generate
better code for stuff like smashable jumps, which I've included in this
diff. (Previously, it was one instruction to compute an address and
another one to load; now it's just a load.)

Reviewed By: @jdelong

Differential Revision: D1017834
2013-10-18 22:18:47 -07:00
Joel Marcey 9e1f0cd094 Stub out two sqlite PDO methods.
Doctrine unit tests calls one of these two methods (sqliteCreateFunction). We fatal because we do not support it. The PHP docs says these functions are experimental, but let's not fatal if we don't have to.

http://www.php.net/manual/en/pdo.sqlitecreatefunction.php

With this diff (and a Doctrine patch that fixes some interface issues it was having), we no longer fatal in Doctrine! We do, however, fail a lot of tests.

Reviewed By: @ptarjan

Differential Revision: D1017386
2013-10-18 22:18:47 -07:00
Joel Marcey 79db99c827 Add Pear and Magento to our test script
Pear and Magento now run correctly with unit testing. I had to do an additional download for PEAR via the new
pull request mechanism, but it works out well. Neither fatal! :)

Reviewed By: @ptarjan

Differential Revision: D1018560
2013-10-18 22:18:47 -07:00
Joel Marcey 952163b9ae Add the pull request that fixes the interface problem with Doctrine
The interface problem ended up being a problem with Dbal (a dependency). This was fixed via a fork from the main dbal repo, but hasn't been merged into the main repo yet.

The script is updated to support pull requests.

Reviewed By: @ptarjan

Differential Revision: D1017683
2013-10-18 22:18:46 -07:00
James Miller 8e87aaa617 update .gitignore for HHVM
Adds a few more filetypes to the HHVM .gitignore

Reviewed By: @ptarjan

Differential Revision: D1015499

Pulled By: @scannell
2013-10-18 22:18:40 -07:00
aravind 7f6e7e9cbe 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-18 22:12:21 -07:00
Brett Simmers 6a41c10cdf Don't truncate HphpArray's allocation size to 32 bits
For arrays that hold ~150 million or more elements, we need to
allocate more than 4GB of ram. computeAllocBytes used to return a uint32_t so
we were truncating the real size and allocating a lot less memory than we
needed.

Reviewed By: @jdelong

Differential Revision: D1016732
2013-10-18 22:12:12 -07:00
Owen Yamauchi df4a7e74da Move function prologues out of tx64
This is the last big chunk of code emission logic in tx64. The path to
getting stuff working in ARM is now blocked by function prologues, so
this needs to happen now.

Function prologues are delicate and messy, so this change isn't 100%
straight code motion.

- The call-array prologue stuff was quite smooth, and all the changes
  are mechanical.

- funcPrologue() turned out to have a pretty big and easily separable
  chunk of x64-specific code in the middle, sandwiched between big
  chunks of platform-agnostic code. I pulled out the platform-specific
  part into the new module I created.

- All the function-guard smashing stuff is very platform-specific so got
  pulled out as well.

Reviewed By: @ottoni

Differential Revision: D1013868
2013-10-18 22:12:08 -07:00
Sean Cannella 12a756085f Better symbol resolution for pprof
Using names more in line with Func::prettyPrint and using full
names for builtins makes it a lot more clear what is going on.

Reviewed By: @hermanventer

Differential Revision: D1016225
2013-10-18 22:12:04 -07:00
Yuval Hager 4b33353789 Support custom reason for status header
Support custom reason for status header

Closes #967
Closes #1183

Reviewed By: afrind

Differential Revision: D1015633

Pulled By: @scannell
2013-10-18 22:11:59 -07:00
Edwin Smith df1ca4c26c Clean up shuffleArgs.
Use smart container, return the move schedule by value,
and do some manual CSE for clarity.

Reviewed By: @jdelong

Differential Revision: D1016082
2013-10-18 22:11:54 -07:00
Eugene Letuchy 0a6adf3bf4 introduce a helper for overwriting an ActRec as cells
... as discussed.

Reviewed By: @jdelong

Differential Revision: D1013186
2013-10-18 22:11:50 -07:00
Jan Oravec b5972e789b Rename ContinuationWaitHandle to AsyncFunctionWaitHandle
- rename ContinuationWaitHandle to AsyncFunctionWaitHandle
- rename onYield hook to onAwait hook

Reviewed By: @billf

Differential Revision: D1016901
2013-10-18 22:11:41 -07:00
Jan Oravec 37ba715ec4 Removed legacy unused callbacks
Remove unused asio_set_on_{started,failed}_callback.

Reviewed By: alexsuhan

Differential Revision: D1016805
2013-10-18 22:11:37 -07:00
seanc 22bc89ab93 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-18 20:01:30 -07:00
Jordan DeLong 094ba8ed5b Initialize m_type when ignoring isTypeVar TypeConstraints
This diff shouldn't change behavior at all; it just
initializes these values so that if you call fullName() on a
TypeConstraint where isTypeVar is true you get a predicatable result.

Reviewed By: @dariorussi

Differential Revision: D1015647
2013-10-17 20:27:25 -07:00
Jordan DeLong be934dc214 Modify test/quick/verify-param-type.php to fail in repo mode; disable it
This test is testing that we don't assume that a successful
parameter type hint implies anything about the type of the parameter,
but we explicitly do this in repo mode.

Reviewed By: @dariorussi

Differential Revision: D1015116
2013-10-17 20:27:25 -07:00
Jordan DeLong 250a811e2b Fix bytecode spec for BareThis
It can push null.

Reviewed By: @swtaarrs

Differential Revision: D1015095
2013-10-17 20:27:25 -07:00
Jordan DeLong 94a523a232 Tweak the format of TypeConstraint::fullName() for !isExtended()
This is currently only used to print the name of a type
constraint when an extended type hint is failing.  I'm using it for
tracing in another context, so I want to it to print different things
for "?Foo" vs "Foo $x = null" hints.

Reviewed By: @dariorussi

Differential Revision: D1014903
2013-10-17 20:27:24 -07:00
Jordan DeLong 1db1c1c0b9 Generate StaticArr for constant arrays
Adding Type::StaticArr was breaking the simplification logic for
OpSame, since it was checking for precise equality of types.

Reviewed By: @edwinsmith

Differential Revision: D719215
2013-10-17 20:27:24 -07:00
Jordan DeLong e7ab1d6c48 Some cleanup to TypeConstraint, expose the DataType/MetaType fields
I need access to the DataType field, and accessing metaType()
directly is more convenient than going through the isFoo functions
(and if you use switch it also means we can get warnings when people
add new metatypes).  Some cleanup along the way (e.g. pull
equivDataTypes out of there, group related members a little more,
etc).

Reviewed By: @dariorussi

Differential Revision: D1014535
2013-10-17 20:27:24 -07:00
Jordan DeLong 72a86a583a 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 20:27:24 -07:00
Eugene Letuchy bbc51c4a89 make 'abstract async' syntax error only behind !(whole program)
... so that production builds (perflab) work for a bit.
 Reverts commit ab87fc08420d56555ade1c5eec1ff4411edf5804.

Reviewed By: @swtaarrs

Differential Revision: D1013669
2013-10-17 20:27:23 -07:00
Andrey Bannikov 7a6a9aa1eb when performing 'out' command, step over next popr
When the 'out' command is issued and flow is inside a called function that will not return value, debugging should continue from the line following the call. We do that by stepping over a PopR if we encounter one after performing 'out'.

Reviewed By: @hermanventer

Differential Revision: D1016061
2013-10-17 20:27:23 -07:00
bsimmers 345aad19ea Fix catch trace issue with inline collection ops
The CheckBounds instruction used to emit two calls to the throw
helper, and we'd try to reference the same catch trace twice. I considered
supporting that but it's faster to just do a single unsigned comparison
anyway. This diff also fixes a case where we'd incorrectly think we were
specializing SetM with a Pair base.

Reviewed By: @jdelong

Differential Revision: D1013820
2013-10-17 20:27:23 -07:00
Stephen Chen dbd5b4d531 instead of rate, use sum to track hhvm's response code
We added rate for tracking hhvm's response code. But this is not a good stats to
use. Rate is defined as (sum / time period). So that means, if we have 59 500s
in the last 1 minute, the rate will still be 0.

Switching to sum will give us better precision and better metric.

This will make it easier for us to monitor the RC roll out.

Reviewed By: jmarch

Differential Revision: D1015363
2013-10-17 20:27:22 -07:00
Brett Simmers 25c9bf57ef Clean up http header initialization code
This diff fixes a few things I ran into while debugging an unrelated
issue:
- The request counter was global and not synchronized. It's not critical for
  there to be no races on this counter but it's not a perf-sensitive path so I
  can't see any reason to not fix it.
- The HeaderMangle warning is now more informative, including the entire set of
  received headers. It also prints at most one warning per request, though that
  warning may have multiple lines.
- The code to actually put the headers in $_SERVER['HTTP_*'] was looping over
  the vector of values for each header, assigning each one to the same key in
  $_SERVER. Unless I'm missing something really subtle, this is equivalent to
  just assigning the final element of the vector to the key, so I changed it to
  do that.

Reviewed By: @markw65

Differential Revision: D1010458
2013-10-17 20:27:22 -07:00
Edwin Smith ba6bc49e63 Remove dead method IRInstruction::setNumSrcs()
Reviewed By: @ottoni

Differential Revision: D1015523
2013-10-17 20:27:22 -07:00
Edwin Smith 1649218428 Rename Jmp_ to Jmp
Reviewed By: @ottoni

Differential Revision: D1015484
2013-10-17 20:27:22 -07:00
bsimmers ccb3ac68b0 Clean up the runtime option to disable refcount opts
It wasn't disabling everything it should.

Reviewed By: @jdelong

Differential Revision: D1013355
2013-10-17 20:27:21 -07:00
Alex Malyshev 73dfe7a892 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 20:27:21 -07:00
Edwin Smith 2a5577435f Don't print lifetime in codegen
This removes some coupling between linear-scan.cpp and codegen.
The lifetime information is based on the linear numbering that
only matters to linear scan.

Reviewed By: @swtaarrs

Differential Revision: D1013874
2013-10-17 20:27:21 -07:00
Jordan DeLong d2762c0a48 Rename LMANY pop descriptor to MMANY
I think this dates back to a time when member instructions
had arg types called "LA", which eventually got renamed, and now "LA"
means local argument.  Rename this.

Reviewed By: @markw65

Differential Revision: D1011765
2013-10-17 20:27:20 -07:00
Jordan DeLong 1d445d8ed7 Add a U stack flavor, for Uninit nulls on the eval stack
The NullUninit opcode implies that cells on the stack can be
uninit pretty much anywhere, but in practice we only need this for
default arguments to FCallBuiltin.  Make that a bytecode invariant
using stack flavors.

Reviewed By: @markw65

Differential Revision: D1011749
2013-10-17 20:27:20 -07:00
Jordan DeLong c4d323fac8 Add AssertT{L,Stk} opcodes, currently for debugging purposes
They assert in debug builds in the interpreter, and cause the
JIT to assume the types are as specified.  I only added a few types
based on my current needs; we can add more as needed, and I didn't
hook it up to any of our region selection or tracelet analyzer stuff.

Reviewed By: @markw65

Differential Revision: D1011114
2013-10-17 20:27:14 -07:00
Bert Maher 60d0e7dad9 Print function in dot output of CFG trace
It's nice to look at profiled CFG's with TRACE=pgo:5.  This
makes it easier to find which one you want to look at.

Reviewed By: @jdelong

Differential Revision: D1013062
2013-10-17 20:27:13 -07:00
Alan Frindell f68fad38d2 make test_server generic
I had previously copied this file for ProxygenServer.  Instead, make it generic so it can test any server.  The "TestServer" test is now "TestLibEventServer".  The new proxygen test includes this source file (as well as main.cpp), so they could perhaps be a library.  I made two tests virtual because the current proxygen instantiation can't pass them.

Reviewed By: @markw65

Differential Revision: D1004360
2013-10-17 20:27:13 -07:00
Alan Frindell ebe1575c98 refactor socket takeover using compostion
Refactor the takeover logic to not be libevent specific, so it can be reused for ProxygenServer.  Creates a takeover agent which handles the socket takeover procedure and ultimately hands off an fd for the caller to use.

Note: it seems to me that the old LibEventServerWithTakeover::stop() had a concurrency bug, because it accessed the eventBase outside of the dispatcher thread.

Reviewed By: @markw65

Differential Revision: D1004326
2013-10-17 20:27:03 -07:00
Alan Frindell d27ddec787 Refactor server fd inheritance using composition
Collapsing the *WithFd functionality directly into LibEventServer.  ProxygenServer will mirror this capability.  Also changed the LibEventServer ctor to take a ServerOptions parameter.

Reviewed By: @markw65

Differential Revision: D1004307
2013-10-17 18:50:03 -07:00
mwilliams 8ea8e65c21 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 18:49:54 -07:00
Jordan DeLong 964a37d43f Remove simplifier case for CheckInitMem
This shouldn't be here, since we don't know what can change
memory locations.

Reviewed By: @swtaarrs

Differential Revision: D1012639
2013-10-17 18:49:42 -07:00
Owen Yamauchi 3680a85130 Miscellaneous ARM fixes to whittle down failure count
- Fix some of the tracelet-guard tests to actually be testing/comparing
  the right thing. I wasn't paying enough attention to byte vs. word
  loads before.

- Don't call EmitLiteralPool unless there are literals. Even if there
  are no literals, if you call that function, vixl emits a "marker"
  instruction so it knows how big the pool is, but that's not needed.

- Add support for stack-chasing through interp-ones of FPushCtor and
  FPushCtorD. Without this, we assert-fail when anything consumes the
  output type of one of these bytecodes, because we've forgotten that
  the output type is Obj.

With this, 180 tests in test/quick fail. The lion's share of them are
due to unimplemented service requests, but there are a few crashes too.
I'll probably go after the unimplemented service requests next.

Reviewed By: @jdelong

Differential Revision: D1009911
2013-10-17 18:49:37 -07:00
Paul Tarjan 905f7e5386 log on invalid php.ini
If you screw up and put a bad config, it should tell you.

Reviewed By: @markw65

Differential Revision: D1013397
2013-10-17 18:49:11 -07:00
Paul Tarjan e3c32c5f8e change test to allow newer libxml2
In versions after 2.7.8 (the one we use) if you parse a poorly formatted xml document, it leaves the bad namespace as part of the node name. In this test, that means it was looking for a function named `ns1:sum`.

I'm making the xml document better formatted. As far as I can tell (from reading their code), zend has this same behavior. They don't have a test with a poorly formatted input.

Here is my cpp test the behaves differently on 2.7.8 and 2.8.0

  #include <libxml/parserInternals.h>
  #include <string.h>
  int main() {
    const char* buf = "<ns1:sum>1</ns1:sum>";
    xmlParserCtxtPtr ctxt = xmlCreateMemoryParserCtxt(buf, strlen(buf));
    ctxt->sax->error = NULL;
    xmlParseDocument(ctxt);
    printf("%s\n", ctxt->myDoc->children->name);
    xmlFreeParserCtxt(ctxt);
  }

compiled with

  /usr/include/libxml2 a.cpp -lxml2 && ./a.out

Reviewed By: @markw65

Differential Revision: D1013435
2013-10-17 18:49:07 -07:00
Paul Tarjan 283579ef6a better empty file warning
Many people have asked what the message you get when you run `hhvm` is. I was thinking of making a real usage thing. Anyone have an idea for the most common use cases? What I have here is better than nothing.

I'm sure there is some fancy C++-ism so I don't need that stupid extra boolean constructor. Input welcome.

Reviewed By: @markw65

Differential Revision: D1013406
2013-10-17 18:49:02 -07:00
bsimmers 2533a2193a Revert "[hphp] easy: parse error for "abstract async""
This reverts commit 061bcc66ac0710fc639cc8c936b9cf68ce45cdf6.

Reviewed By: @elgenie
2013-10-17 18:48:58 -07:00
Paul Tarjan 45fa5837fc don't hardcode name in test
this test has nothing to do with the stderr, so lets not require that we can write to some random file

Reviewed By: @markw65

Differential Revision: D1013443
2013-10-17 18:48:45 -07:00
James Miller 467c1a8024 Make the embedded systemlib a dependency of the binary 2013-10-17 15:54:38 -07:00
Sara Golemon b04bae25f3 Merge pull request #1184 from PocketRent/fix-install
Fix broken make install behaviour
2013-10-17 15:36:08 -07:00
Sean Cannella 8f574018aa Merge pull request #1185 from kandy/patch-2
Travis CI banner url update due to GitHub project name change
2013-10-17 07:32:20 -07:00
Andrii Kasian cae20c2e28 Travis CI banner path update 2013-10-17 08:40:19 +03:00
James Miller 4f3652034d 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 16:31:38 +13:00
Sara Golemon 75a3806bae Master is now working towards 2.3.0 2013-10-16 11:19:10 -07:00
14407 arquivos alterados com 872744 adições e 200391 exclusões
+4 -19
Ver Arquivo
@@ -1,10 +1,5 @@
*.[oad]
*.hhbc
/bin*-g
/bin*-O
/bin/*.so
/bin/hphp_options
/bin/systemlib.php
.mkdir
hphp.log
@@ -37,16 +32,8 @@ hphp.log
/hphp/hhvm/gen
/hphp/hhvm/hhvm
/hphp/runtime/ext/*.ext_hhvm.cpp
/hphp/runtime/ext/*.ext_hhvm.h
/hphp/runtime/ext/*/*.ext_hhvm.cpp
/hphp/runtime/ext/*/*.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
*.ext_hhvm.cpp
*.ext_hhvm.h
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.cpp
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.h
@@ -55,10 +42,6 @@ hphp.log
/hphp/ffi/java/classes
/hphp/ffi/java/hphp_ffi_java.h
# Ignore all makefiles generated for fbcode's third-party repo
/bin/*.mk
!/bin/run.mk
CMakeFiles
CMakeCache.txt
cmake_install.cmake
@@ -68,6 +51,8 @@ install_manifest.txt
/hphp/TAGS
/hphp/third_party/libzip/libzip.dylib
# Generated makefiles
/hphp/runtime/ext_hhvm/Makefile
/hphp/test/Makefile
+3
Ver Arquivo
@@ -0,0 +1,3 @@
[submodule "hphp/submodules/folly"]
path = hphp/submodules/folly
url = git://github.com/facebook/folly.git
+20 -8
Ver Arquivo
@@ -4,23 +4,35 @@ compiler:
- gcc
before_script:
- TRAVIS=1 ./configure_ubuntu_12.04.sh
- time 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 6
- time sudo locale-gen de_DE && sudo locale-gen zh_CN.utf8 && sudo locale-gen fr_FR
- time HPHP_HOME=`pwd` make -j 6
# mysql configuration for unit-tests
- mysql -e 'CREATE DATABASE IF NOT EXISTS hhvm;'
- export PDO_MYSQL_TEST_DSN="mysql:host=127.0.0.1;dbname=hhvm"
- export PDO_MYSQL_TEST_USER="travis"
- export PDO_MYSQL_TEST_PASS=""
# 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 quick"
- TEST_RUN_MODE="-m jit slow"
- TEST_RUN_MODE="-m jit zend"
- TEST_RUN_MODE="-m jit -r quick"
- TEST_RUN_MODE="-m jit -r slow"
- TEST_RUN_MODE="-m jit -r zend"
- TEST_RUN_MODE="-m interp quick"
- TEST_RUN_MODE="-m interp slow"
- TEST_RUN_MODE="-m interp zend"
- TEST_RUN_MODE="-m interp -r quick"
- TEST_RUN_MODE="-m interp -r slow"
- TEST_RUN_MODE="-m interp -r zend"
script: hphp/hhvm/hhvm hphp/test/run $TEST_RUN_MODE
script: time hphp/hhvm/hhvm hphp/test/run $TEST_RUN_MODE
notifications:
email: false
irc: "chat.freenode.net#hhvm"
+61
Ver Arquivo
@@ -0,0 +1,61 @@
option(ENABLE_ZEND_COMPAT "Enable Zend source compatibility (beta)" OFF)
set(ZEND_COMPAT_PROJECTS)
set(ZEND_COMPAT_BUILD_DIRS)
set(ZEND_COMPAT_EXCLUDE_IDLS)
set(ZEND_COMPAT_LINK_LIBRARIES)
# Look for projects
set(EZC_DIR "${HPHP_HOME}/hphp/runtime/ext_zend_compat/")
file(GLOB ezc_projects RELATIVE ${EZC_DIR} "${EZC_DIR}/*")
foreach(ezc_project ${ezc_projects})
get_filename_component(ezc_name ${ezc_project} NAME)
if ((NOT ${ezc_name} STREQUAL "php-src") AND (IS_DIRECTORY "${EZC_DIR}/${ezc_name}"))
list(APPEND ZEND_COMPAT_PROJECTS ${ezc_name})
endif()
endforeach()
if (ENABLE_ZEND_COMPAT)
foreach(ezc_project ${ZEND_COMPAT_PROJECTS})
if (${ezc_project} STREQUAL "yaml")
find_package(LibYaml)
if (LibYaml_INCLUDE_DIRS)
list(APPEND ZEND_COMPAT_BUILD_DIRS "${EZC_DIR}/yaml")
include_directories(${LibYaml_INCLUDE_DIRS})
list(APPEND ZEND_COMPAT_LINK_LIBRARIES ${LibYaml_LIBRARIES})
else()
list(APPEND ZEND_COMPAT_EXCLUDE_IDLS "yaml.idl.json")
endif()
elseif (${ezc_project} STREQUAL "mongo")
include_directories("${EZC_DIR}/mongo/mcon")
list(APPEND ZEND_COMPAT_BUILD_DIRS "${EZC_DIR}/mongo")
else()
list(APPEND ZEND_COMPAT_BUILD_DIRS "${EZC_DIR}/${ezc_project}")
endif()
endforeach()
if (ZEND_COMPAT_BUILD_DIRS)
list(APPEND ZEND_COMPAT_BUILD_DIRS "${EZC_DIR}/php-src")
include_directories("${EZC_DIR}/php-src")
include_directories("${EZC_DIR}/php-src/main")
include_directories("${EZC_DIR}/php-src/Zend")
include_directories("${EZC_DIR}/php-src/TSRM")
endif()
else()
foreach(ezc_project ${ZEND_COMPAT_PROJECTS})
list(APPEND ZEND_COMPAT_EXCLUDE_IDLS "${ezc_project}.idl.json")
endforeach()
endif()
# This is really ugly, but cmake's list(FIND)
# doesn't entirely work the way it should
macro(ZEND_COMPAT_STRIP_IDLS IDLS)
foreach(idl ${${IDLS}})
get_filename_component(idl_name ${idl} NAME)
foreach(f ${ARGV})
if (${idl_name} STREQUAL ${f})
list(REMOVE_ITEM ${IDLS} ${idl})
endif()
endforeach()
endforeach()
endmacro()
+16
Ver Arquivo
@@ -0,0 +1,16 @@
find_package(PkgConfig)
pkg_check_modules(PC_FREETYPE QUIET freetype2)
find_path(FREETYPE_INCLUDE_DIRS NAMES freetype/config/ftheader.h
HINTS ${PC_FREETYPE_INCLUDEDIR} ${PC_FREETYPE_INCLUDE_DIRS}
PATH_SUFFIXES freetype2)
find_library(FREETYPE_LIBRARIES NAMES freetype)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Freetype DEFAULT_MSG
FREETYPE_LIBRARIES
FREETYPE_INCLUDE_DIRS)
mark_as_advanced(FREETYPE_INCLUDE_DIRS FREETYPE_LIBRARIES)
-121
Ver Arquivo
@@ -1,121 +0,0 @@
# - Find GD
# Find the native GD includes and library
# This module defines
# GD_INCLUDE_DIR, where to find gd.h, etc.
# GD_LIBRARIES, the libraries needed to use GD.
# GD_FOUND, If false, do not try to use GD.
# also defined, but not for general use are
# GD_LIBRARY, where to find the GD library.
# GD_SUPPORTS_PNG, GD_SUPPORTS_JPEG, GD_SUPPORTS_GIF, test
# support for image formats in GD.
FIND_PATH(GD_INCLUDE_DIR gd.h
/usr/local/include
/usr/include
)
if(WIN32 AND NOT CYGWIN)
SET(GD_NAMES ${GD_NAMES} bgd)
else(WIN32)
SET(GD_NAMES ${GD_NAMES} gd)
endif(WIN32 AND NOT CYGWIN)
FIND_LIBRARY(GD_LIBRARY
NAMES ${GD_NAMES}
PATHS /usr/lib64 /usr/lib /usr/local/lib
)
IF (GD_LIBRARY AND GD_INCLUDE_DIR)
SET(GD_LIBRARIES ${GD_LIBRARY})
SET(GD_FOUND "YES")
ELSE (GD_LIBRARY AND GD_INCLUDE_DIR)
SET(GD_FOUND "NO")
ENDIF (GD_LIBRARY AND GD_INCLUDE_DIR)
IF (GD_FOUND)
IF (WIN32 AND NOT CYGWIN)
SET(GD_SUPPORTS_PNG ON)
SET(GD_SUPPORTS_JPEG ON)
SET(GD_SUPPORTS_GIF ON)
get_filename_component(GD_LIBRARY_DIR ${GD_LIBRARY} PATH)
ELSE (WIN32 AND NOT CYGWIN)
INCLUDE(CheckLibraryExists)
GET_FILENAME_COMPONENT(GD_LIB_PATH ${GD_LIBRARY} PATH)
GET_FILENAME_COMPONENT(GD_LIB ${GD_LIBRARY} NAME)
CHECK_LIBRARY_EXISTS("${GD_LIBRARY}" "gdImagePng" "${GD_LIB_PATH}" GD_SUPPORTS_PNG)
IF (GD_SUPPORTS_PNG)
find_package(PNG)
IF (PNG_FOUND)
SET(GD_LIBRARIES ${GD_LIBRARIES} ${PNG_LIBRARIES})
SET(GD_INCLUDE_DIR ${GD_INCLUDE_DIR} ${PNG_INCLUDE_DIR})
ELSE (PNG_FOUND)
SET(GD_SUPPORTS_PNG "NO")
ENDIF (PNG_FOUND)
ENDIF (GD_SUPPORTS_PNG)
CHECK_LIBRARY_EXISTS("${GD_LIBRARY}" "gdImageJpeg" "${GD_LIB_PATH}" GD_SUPPORTS_JPEG)
IF (GD_SUPPORTS_JPEG)
find_package(JPEG)
IF (JPEG_FOUND)
SET(GD_LIBRARIES ${GD_LIBRARIES} ${JPEG_LIBRARIES})
SET(GD_INCLUDE_DIR ${GD_INCLUDE_DIR} ${JPEG_INCLUDE_DIR})
ELSE (JPEG_FOUND)
SET(GD_SUPPORTS_JPEG "NO")
ENDIF (JPEG_FOUND)
ENDIF (GD_SUPPORTS_JPEG)
CHECK_LIBRARY_EXISTS("${GD_LIBRARY}" "gdImageGif" "${GD_LIB_PATH}" GD_SUPPORTS_GIF)
# Trim the list of include directories
SET(GDINCTRIM)
FOREACH(GD_DIR ${GD_INCLUDE_DIR})
SET(GD_TMP_FOUND OFF)
FOREACH(GD_TRIMMED ${GDINCTRIM})
IF ("${GD_DIR}" STREQUAL "${GD_TRIMMED}")
SET(GD_TMP_FOUND ON)
ENDIF ("${GD_DIR}" STREQUAL "${GD_TRIMMED}")
ENDFOREACH(GD_TRIMMED ${GDINCTRIM})
IF (NOT GD_TMP_FOUND)
SET(GDINCTRIM "${GDINCTRIM}" "${GD_DIR}")
ENDIF (NOT GD_TMP_FOUND)
ENDFOREACH(GD_DIR ${GD_INCLUDE_DIR})
SET(GD_INCLUDE_DIR ${GDINCTRIM})
SET(GD_LIBRARY_DIR)
# Generate trimmed list of library directories and list of libraries
FOREACH(GD_LIB ${GD_LIBRARIES})
GET_FILENAME_COMPONENT(GD_NEXTLIBDIR ${GD_LIB} PATH)
SET(GD_TMP_FOUND OFF)
FOREACH(GD_LIBDIR ${GD_LIBRARY_DIR})
IF ("${GD_NEXTLIBDIR}" STREQUAL "${GD_LIBDIR}")
SET(GD_TMP_FOUND ON)
ENDIF ("${GD_NEXTLIBDIR}" STREQUAL "${GD_LIBDIR}")
ENDFOREACH(GD_LIBDIR ${GD_LIBRARIES})
IF (NOT GD_TMP_FOUND)
SET(GD_LIBRARY_DIR "${GD_LIBRARY_DIR}" "${GD_NEXTLIBDIR}")
ENDIF (NOT GD_TMP_FOUND)
ENDFOREACH(GD_LIB ${GD_LIBRARIES})
ENDIF (WIN32 AND NOT CYGWIN)
ENDIF (GD_FOUND)
IF (GD_FOUND)
IF (NOT GD_FIND_QUIETLY)
MESSAGE(STATUS "Found GD: ${GD_LIBRARY}")
ENDIF (NOT GD_FIND_QUIETLY)
ELSE (GD_FOUND)
IF (GD_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "Could not find GD library")
ENDIF (GD_FIND_REQUIRED)
ENDIF (GD_FOUND)
MARK_AS_ADVANCED(
GD_LIBRARY
GD_LIBRARIES
GD_INCLUDE_DIR
GD_LIBRARY_DIR
GD_SUPPORTS_PNG
GD_SUPPORTS_JPEG
GD_SUPPORTS_GIF
)
+1 -1
Ver Arquivo
@@ -21,7 +21,7 @@ CHECK_C_SOURCE_RUNS("#include <dlfcn.h>
void testfunc() {}
int main() {
testfunc();
return dyslm(0, "_testfunc") != (void*)0;
return dyslm(0, \"_testfunc\") != (void*)0;
}" LIBDL_NEEDS_UNDERSCORE)
mark_as_advanced(LIBDL_INCLUDE_DIRS LIBDL_LIBRARIES LIBDL_NEEDS_UNDERSCORE)
+9 -1
Ver Arquivo
@@ -18,7 +18,7 @@ endif (LIBDWARF_LIBRARIES AND LIBDWARF_INCLUDE_DIRS)
find_path (DWARF_INCLUDE_DIR
NAMES
dwarf.h
libdwarf.h dwarf.h
PATHS
/usr/include
/usr/include/libdwarf
@@ -50,5 +50,13 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDwarf DEFAULT_MSG
LIBDWARF_LIBRARIES
LIBDWARF_INCLUDE_DIRS)
if (LIBDWARF_LIBRARIES AND LIBDWARF_INCLUDE_DIRS)
set(CMAKE_REQUIRED_INCLUDES ${LIBDWARF_INCLUDE_DIRS})
set(CMAKE_REQUIRED_LIBRARIES ${LIBDWARF_LIBRARIES})
include(CheckSymbolExists)
CHECK_SYMBOL_EXISTS(dwarf_encode_leb128 "libdwarf.h" LIBDWARF_HAVE_ENCODE_LEB128)
endif()
mark_as_advanced(LIBDW_INCLUDE_DIR DWARF_INCLUDE_DIR)
mark_as_advanced(LIBDWARF_INCLUDE_DIRS LIBDWARF_LIBRARIES)
mark_as_advanced(LIBDWARF_HAVE_ENCODE_LEB128)
+14
Ver Arquivo
@@ -0,0 +1,14 @@
if (LIBJPEG_LIBRARIES AND LIBJPEG_INCLUDE_DIRS)
set (LibJpeg_FIND_QUIETLY TRUE)
endif (LIBJPEG_LIBRARIES AND LIBJPEG_INCLUDE_DIRS)
find_path(LIBJPEG_INCLUDE_DIRS NAMES jpeglib.h)
find_library(LIBJPEG_LIBRARIES NAMES jpeg)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibJpeg DEFAULT_MSG
LIBJPEG_LIBRARIES
LIBJPEG_INCLUDE_DIRS)
mark_as_advanced(LIBJPEG_INCLUDE_DIRS LIBJPEG_LIBRARIES)
+14
Ver Arquivo
@@ -0,0 +1,14 @@
if (LIBPNG_LIBRARIES AND LIBPNG_INCLUDE_DIRS)
set (LibPng_FIND_QUIETLY TRUE)
endif (LIBPNG_LIBRARIES AND LIBPNG_INCLUDE_DIRS)
find_path(LIBPNG_INCLUDE_DIRS NAMES png.h)
find_library(LIBPNG_LIBRARIES NAMES png)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibPng DEFAULT_MSG
LIBPNG_LIBRARIES
LIBPNG_INCLUDE_DIRS)
mark_as_advanced(LIBPNG_INCLUDE_DIRS LIBPNG_LIBRARIES)
+12
Ver Arquivo
@@ -0,0 +1,12 @@
if (LIBODBC_LIBRARIES AND LIBODBC_INCLUDE_DIRS)
set (LibUODBC_FIND_QUIETLY TRUE)
endif (LIBODBC_LIBRARIES AND LIBODBC_INCLUDE_DIRS)
find_path (LIBODBC_INCLUDE_DIRS NAMES sqlext.h)
find_library (LIBODBC_LIBRARIES NAMES odbc)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibUODBC DEFAULT_MSG
LIBODBC_LIBRARIES
LIBODBC_INCLUDE_DIRS)
mark_as_advanced(LIBODBC_INCLUDE_DIRS LIBODBC_LIBRARIES)
+14
Ver Arquivo
@@ -0,0 +1,14 @@
if (LIBVPX_LIBRARIES AND LIBVPX_INCLUDE_DIRS)
set (LibVpx_FIND_QUIETLY TRUE)
endif (LIBVPX_LIBRARIES AND LIBVPX_INCLUDE_DIRS)
find_path(LIBVPX_INCLUDE_DIRS NAMES vpx_codec.h)
find_library(LIBVPX_LIBRARIES NAMES vpx)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibVpx DEFAULT_MSG
LIBVPX_LIBRARIES
LIBVPX_INCLUDE_DIRS)
mark_as_advanced(LIBVPX_INCLUDE_DIRS LIBVPX_LIBRARIES)
+13
Ver Arquivo
@@ -0,0 +1,13 @@
if (LibYaml_LIBRARIES AND LibYaml_INCLUDE_DIRS)
set (LibYaml_FIND_QUIETLY TRUE)
endif (LibYaml_LIBRARIES AND LibYaml_INCLUDE_DIRS)
find_path (LibYaml_INCLUDE_DIRS NAMES yaml.h)
find_library (LibYaml_LIBRARIES NAMES yaml)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibYaml DEFAULT_MSG
LibYaml_LIBRARIES
LibYaml_INCLUDE_DIRS)
mark_as_advanced(LibYaml_INCLUDE_DIRS LibYaml_LIBRARIES)
+28
Ver Arquivo
@@ -0,0 +1,28 @@
# folly-config.h is a generated file from autotools
# We need to do the equivalent checks here and use
# add_definitions as needed
add_definitions(-DFOLLY_NO_CONFIG=1)
INCLUDE(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("
extern \"C\" void (*test_ifunc(void))() { return 0; }
void func() __attribute__((ifunc(\"test_ifunc\")));
" FOLLY_IFUNC)
if (FOLLY_IFUNC)
add_definitions("-DHAVE_IFUNC=1")
endif()
set(CMAKE_REQUIRED_LIBRARIES rt)
include(CheckFunctionExists)
CHECK_FUNCTION_EXISTS("clock_gettime" HAVE_CLOCK_GETTIME)
if (HAVE_CLOCK_GETTIME)
add_definitions("-DFOLLY_HAVE_CLOCK_GETTIME=1")
endif()
set(CMAKE_REQUIRED_LIBRARIES)
find_path(FEATURES_H_INCLUDE_DIR NAMES features.h)
if (FEATURES_H_INCLUDE_DIR)
include_directories("${FEATURES_H_INCLUDE_DIR}")
add_definitions("-DFOLLY_HAVE_FEATURES_H=1")
endif()
+12 -17
Ver Arquivo
@@ -1,14 +1,5 @@
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
@@ -16,6 +7,10 @@ int main() { return 0; }" HAVE_GCC_46)
#endif
int main() { return 0; }" HAVE_GCC_47)
if (NOT HAVE_GCC_47)
message(FATAL_ERROR "Need at least GCC 4.7")
endif()
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40800
#error Not GCC 4.8.0+
@@ -37,18 +32,18 @@ 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")
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-180 -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 "")
set(GNUCC_48_OPT "")
if(HAVE_GCC_48)
set(GNUCC_LOCAL_TYPEDEF_OPT "-Wno-unused-local-typedefs")
set(GNUCC_48_OPT "-Wno-unused-local-typedefs -fno-canonical-system-headers -Wno-deprecated-declarations")
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}")
set(CMAKE_CXX_FLAGS "-fno-gcse -fno-omit-frame-pointer -ftemplate-depth-180 -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++11 -Werror=format-security -Wno-unused-result -Wno-sign-compare -Wno-attributes -Wno-maybe-uninitialized -mcrc32 ${GNUCC_48_OPT}")
endif()
if(${CMAKE_CXX_COMPILER} MATCHES ".*clang.*")
set(CMAKE_CXX_FLAGS "-fno-gcse -fno-omit-frame-pointer -ftemplate-depth-180 -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++11 -Werror=format-security -Wno-unused-result -Wno-sign-compare -Wno-attributes -Wno-maybe-uninitialized -Wno-mismatched-tags -Wno-unknown-warning-option -Wno-return-type-c-linkage -Qunused-arguments")
endif()
if(CMAKE_COMPILER_IS_GNUCC)
+77 -20
Ver Arquivo
@@ -31,6 +31,11 @@ endif()
find_package(Boost 1.48.0 COMPONENTS system program_options filesystem regex REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
# Boost 1.49 supports a better flat_multimap, but 1.48 is good enough
if (Boost_VERSION GREATER 104899)
add_definitions("-DHAVE_BOOST1_49")
endif()
# features.h
FIND_PATH(FEATURES_HEADER features.h)
@@ -85,22 +90,46 @@ include_directories(${LIBEVENT_INCLUDE_DIR})
set(CMAKE_REQUIRED_LIBRARIES "${LIBEVENT_LIB}")
CHECK_FUNCTION_EXISTS("evhttp_bind_socket_with_fd" HAVE_CUSTOM_LIBEVENT)
if (NOT HAVE_CUSTOM_LIBEVENT)
unset(HAVE_CUSTOM_LIBEVENT CACHE)
unset(LIBEVENT_INCLUDE_DIR CACHE)
unset(LIBEVENT_LIB CACHE)
unset(LibEvent_FOUND CACHE)
message(FATAL_ERROR "Custom libevent is required with HipHop patches")
endif ()
if(HAVE_CUSTOM_LIBEVENT)
message("Using custom LIBEVENT")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DHAVE_CUSTOM_LIBEVENT")
endif()
set(CMAKE_REQUIRED_LIBRARIES)
# GD checks
find_package(GD REQUIRED)
find_package(LibUODBC)
if (LIBUODBC_INCLUDE_DIRS)
include_directories(${LIBUODBC_INCLUDE_DIRS})
add_definitions("-DHAVE_UODBC")
endif ()
# GD checks
add_definitions(-DPNG_SKIP_SETJMP_CHECK)
find_package(LibVpx)
if (LIBVPX_INCLUDE_DIRS)
include_directories(${LIBVPX_INCLUDE_DIRS})
add_definitions("-DHAVE_GD_WEBP")
endif()
find_package(LibJpeg)
if (LIBJPEG_INCLUDE_DIRS)
include_directories(${LIBJPEG_INCLUDE_DIRS})
add_definitions("-DHAVE_GD_JPG")
endif()
find_package(LibPng)
if (LIBPNG_INCLUDE_DIRS)
include_directories(${LIBPNG_INCLUDE_DIRS})
add_definitions("-DHAVE_GD_PNG")
endif()
find_package(Freetype)
if (FREETYPE_INCLUDE_DIRS)
include_directories(${FREETYPE_INCLUDE_DIRS})
add_definitions("-DHAVE_LIBFREETYPE -DHAVE_GD_FREETYPE -DENABLE_GD_TTF")
endif()
# libXed
find_package(LibXed)
if (LibXed_INCLUDE_DIR AND LibXed_LIBRARY)
include_directories(${LibXed_INCLUDE_DIR})
add_definitions(-DHAVE_LIBXED)
add_definitions("-DHAVE_LIBXED")
endif()
# CURL checks
@@ -136,6 +165,7 @@ include_directories("${HPHP_HOME}/hphp/third_party/libmbfl/filter")
include_directories("${HPHP_HOME}/hphp/third_party/lz4")
include_directories("${HPHP_HOME}/hphp/third_party/double-conversion/src")
include_directories("${HPHP_HOME}/hphp/third_party/folly")
include_directories("${HPHP_HOME}/hphp/third_party/libzip")
# ICU
find_package(ICU REQUIRED)
@@ -289,6 +319,9 @@ include_directories(${CCLIENT_INCLUDE_PATH})
find_package(LibDwarf REQUIRED)
include_directories(${LIBDWARF_INCLUDE_DIRS})
if (LIBDWARF_HAVE_ENCODE_LEB128)
add_definitions("-DHAVE_LIBDWARF_20130729")
endif()
find_package(LibElf REQUIRED)
include_directories(${LIBELF_INCLUDE_DIRS})
@@ -302,17 +335,26 @@ if (NOT RECENT_CCLIENT)
message(FATAL_ERROR "Your version of c-client is too old, you need 2007")
endif()
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/linkage.h" auth_gss CCLIENT_NEEDS_PAM)
if (EXISTS "${CCLIENT_INCLUDE_PATH}/linkage.c")
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/linkage.c" auth_gss CCLIENT_HAS_GSS)
elseif (EXISTS "${CCLIENT_INCLUDE_PATH}/linkage.h")
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/linkage.h" auth_gss CCLIENT_HAS_GSS)
endif()
find_package(Libpam)
if (PAM_INCLUDE_PATH)
include_directories(${PAM_INCLUDE_PATH})
endif()
if (NOT CCLIENT_HAS_GSS)
add_definitions(-DSKIP_IMAP_GSS=1)
endif()
if (EXISTS "${CCLIENT_INCLUDE_PATH}/linkage.c")
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/linkage.c" ssl_onceonlyinit CCLIENT_HAS_SSL)
endif()
if (CCLIENT_NEEDS_PAM)
find_package(Libpam REQUIRED)
include_directories(${PAM_INCLUDE_PATH})
else()
add_definitions(-DSKIP_IMAP_GSS=1)
elseif (EXISTS "${CCLIENT_INCLUDE_PATH}/linkage.h")
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/linkage.h" ssl_onceonlyinit CCLIENT_HAS_SSL)
endif()
if (NOT CCLIENT_HAS_SSL)
@@ -446,7 +488,21 @@ endif()
target_link_libraries(${target} ${ONIGURUMA_LIBRARIES})
target_link_libraries(${target} ${Mcrypt_LIB})
target_link_libraries(${target} ${GD_LIBRARY})
if (FREETYPE_LIBRARIES)
target_link_libraries(${target} ${FREETYPE_LIBRARIES})
endif()
if (LIBJPEG_LIBRARIES)
target_link_libraries(${target} ${LIBJPEG_LIBRARIES})
endif()
if (LIBPNG_LIBRARIES)
target_link_libraries(${target} ${LIBPNG_LIBRARIES})
endif()
if (LIBVPX_LIBRARIES)
target_link_libraries(${target} ${LIBVPX_LIBRARIES})
endif()
if (LIBUODBC_LIBRARIES)
target_link_libraries(${target} ${LIBUODBC_LIBRARIES})
endif()
target_link_libraries(${target} ${LDAP_LIBRARIES})
target_link_libraries(${target} ${LBER_LIBRARIES})
@@ -462,6 +518,7 @@ endif()
target_link_libraries(${target} lz4)
target_link_libraries(${target} double-conversion)
target_link_libraries(${target} folly)
target_link_libraries(${target} zip_static)
target_link_libraries(${target} afdt)
target_link_libraries(${target} mbfl)
@@ -475,7 +532,7 @@ endif()
target_link_libraries(${target} ${NCURSES_LIBRARY})
target_link_libraries(${target} ${CCLIENT_LIBRARY})
if (CCLIENT_NEEDS_PAM)
if (PAM_LIBRARY)
target_link_libraries(${target} ${PAM_LIBRARY})
endif()
+61 -5
Ver Arquivo
@@ -38,6 +38,27 @@ function(auto_sources RETURN_VALUE PATTERN SOURCE_SUBDIRS)
set(${RETURN_VALUE} ${${RETURN_VALUE}} PARENT_SCOPE)
endfunction(auto_sources)
macro(HHVM_SELECT_SOURCES DIR)
auto_sources(files "*.cpp" "RECURSE" "${DIR}")
foreach(f ${files})
if (NOT (${f} MATCHES "(ext_hhvm|/(old-)?tests?/)"))
list(APPEND CXX_SOURCES ${f})
endif()
endforeach()
auto_sources(files "*.c" "RECURSE" "${DIR}")
foreach(f ${files})
if (NOT (${f} MATCHES "(ext_hhvm|/(old-)?tests?/)"))
list(APPEND C_SOURCES ${f})
endif()
endforeach()
auto_sources(files "*.S" "RECURSE" "${DIR}")
foreach(f ${files})
if (NOT (${f} MATCHES "(ext_hhvm|/(old-)?tests?/)"))
list(APPEND ASM_SOURCES ${f})
endif()
endforeach()
endmacro(HHVM_SELECT_SOURCES)
function(CONTAINS_STRING FILE SEARCH RETURN_VALUE)
file(STRINGS ${FILE} FILE_CONTENTS REGEX ".*${SEARCH}.*")
if (FILE_CONTENTS)
@@ -68,17 +89,52 @@ macro(MYSQL_SOCKET_SEARCH)
endif()
endmacro()
function(embed_systemlib TARGET DEST SOURCE)
function(embed_systemlib TARGET DEST SOURCE SECTNAME)
if (APPLE)
target_link_libraries(${TARGET} -Wl,-sectcreate,__text,systemlib,${SOURCE})
target_link_libraries(${TARGET} -Wl,-sectcreate,__text,${SECTNAME},${SOURCE})
else()
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND "objcopy"
ARGS "--add-section" "systemlib=${SOURCE}" ${DEST}
COMMENT "Embedding systemlib.php in ${TARGET}")
ARGS "--add-section" "${SECTNAME}=${SOURCE}" ${DEST}
COMMENT "Embedding ${SOURCE} in ${TARGET} as ${SECTNAME}")
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)
function(embed_all_systemlibs TARGET DEST)
embed_systemlib(${TARGET} ${DEST} ${HPHP_HOME}/hphp/system/systemlib.php systemlib)
auto_sources(SYSTEMLIBS "ext_*.php" "RECURSE" "${HPHP_HOME}/hphp/runtime")
foreach(SLIB ${SYSTEMLIBS})
get_filename_component(SLIB_BN ${SLIB} "NAME_WE")
string(LENGTH ${SLIB_BN} SLIB_BN_LEN)
math(EXPR SLIB_BN_REL_LEN "${SLIB_BN_LEN} - 4")
string(SUBSTRING ${SLIB_BN} 4 ${SLIB_BN_REL_LEN} SLIB_EXTNAME)
string(MD5 SLIB_HASH_NAME ${SLIB_EXTNAME})
string(SUBSTRING ${SLIB_HASH_NAME} 0 12 SLIB_HASH_NAME_SHORT)
embed_systemlib(${TARGET} ${DEST} ${SLIB} "ext.${SLIB_HASH_NAME_SHORT}")
endforeach()
endfunction(embed_all_systemlibs)
# 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})
@@ -87,5 +143,5 @@ function(HHVM_EXTENSION EXTNAME)
endfunction()
function(HHVM_SYSTEMLIB EXTNAME SOURCE_FILE)
embed_systemlib(${EXTNAME} "${EXTNAME}.so" ${SOURCE_FILE})
embed_systemlib(${EXTNAME} "${EXTNAME}.so" ${SOURCE_FILE} systemlib)
endfunction()
+35 -4
Ver Arquivo
@@ -1,9 +1,18 @@
include(Options)
if (APPLE)
# Do this until cmake has a define for ARMv8
INCLUDE(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("
#ifndef __AARCH64EL__
#error Not ARMv8
#endif
int main() { return 0; }" IS_AARCH64)
if (APPLE OR IS_AARCH64)
set(HHVM_ANCHOR_SYMS -Wl,-u,_register_libevent_server)
else()
set(HHVM_ANCHOR_SYMS -Wl,-uregister_libevent_server)
set(ENABLE_FASTCGI 1)
set(HHVM_ANCHOR_SYMS -Wl,-uregister_libevent_server,-uregister_fastcgi_server)
endif()
set(HHVM_LINK_LIBRARIES
@@ -14,9 +23,15 @@ set(HHVM_LINK_LIBRARIES
hphp_parser
hphp_zend
hphp_util
hphp_hhbbc
vixl neo
${HHVM_ANCHOR_SYMS})
if(ENABLE_FASTCGI)
LIST(APPEND HHVM_LINK_LIBRARIES hphp_thrift)
LIST(APPEND HHVM_LINK_LIBRARIES hphp_proxygen)
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif()
@@ -25,6 +40,15 @@ IF(NOT DEFINED CMAKE_PREFIX_PATH)
message(STATUS "CMAKE_PREFIX_PATH was missing, proceeding anyway")
endif()
# 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}")
if(APPLE)
@@ -38,8 +62,7 @@ include(HPHPCompiler)
include(HPHPFunctions)
include(HPHPFindLibs)
add_definitions(-D_REENTRANT=1 -D_PTHREADS=1 -D__STDC_FORMAT_MACROS)
add_definitions(-DHHVM_LIB_PATH_DEFAULT="${HPHP_HOME}/bin")
add_definitions(-D_REENTRANT=1 -D_PTHREADS=1 -D__STDC_FORMAT_MACROS -DFOLLY_HAVE_WEAK_SYMBOLS=1)
if (LINUX)
add_definitions(-D_GNU_SOURCE)
@@ -96,6 +119,14 @@ if(APPLE)
add_definitions(-DMACOSX_DEPLOYMENT_TARGET=10.6)
endif()
if(ENABLE_FASTCGI)
add_definitions(-DENABLE_FASTCGI=1)
endif ()
if(DISABLE_HARDWARE_COUNTERS)
add_definitions(-DNO_HARDWARE_COUNTERS=1)
endif ()
# enable the OSS options if we have any
add_definitions(-DHPHP_OSS=1)
+3
Ver Arquivo
@@ -13,3 +13,6 @@ option(USE_JEMALLOC "Use jemalloc" ON)
option(USE_TCMALLOC "Use tcmalloc (if jemalloc is not used)" ON)
option(USE_GOOGLE_HEAP_PROFILER "Use Google heap profiler" OFF)
option(USE_GOOGLE_CPU_PROFILER "Use Google cpu profiler" OFF)
option(DISABLE_HARDWARE_COUNTERS "Disable hardware counters (for XenU systems)" OFF)
+11 -21
Ver Arquivo
@@ -1,18 +1,18 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.5 FATAL_ERROR)
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.7 FATAL_ERROR)
PROJECT(hphp C CXX ASM)
IF("$ENV{HPHP_HOME}" STREQUAL "")
message(FATAL_ERROR "You should set the HPHP_HOME environmental")
IF(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
message(FATAL_ERROR "HHVM requires a 64bit OS")
ENDIF()
file(TO_CMAKE_PATH "$ENV{HPHP_HOME}" HPHP_HOME)
set(HPHP_HOME "$ENV{HPHP_HOME}")
if (NOT HPHP_HOME)
set(HPHP_HOME "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
message("Using HPHP_HOME == ${HPHP_HOME}")
IF(NOT IS_DIRECTORY ${HPHP_HOME})
message(FATAL_ERROR "The value of HPHP_HOME does not exist")
ENDIF()
IF(NOT EXISTS "${HPHP_HOME}/LICENSE.PHP")
message(FATAL_ERROR "The value of HPHP_HOME in incorrect")
IF(NOT EXISTS "${HPHP_HOME}/CMake/HPHPSetup.cmake")
message(FATAL_ERROR "Invalid HPHP_HOME. Set it to the root of your hhvm tree, or run `cmake .` from there.")
ENDIF()
SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake" ${CMAKE_MODULE_PATH})
@@ -20,15 +20,5 @@ SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake" ${CMAKE_MODULE_PATH})
include("${CMAKE_CURRENT_SOURCE_DIR}/CMake/HPHPFunctions.cmake")
include(CheckFunctionExists)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/hphp)
add_subdirectory(hphp)
IF(CMAKE_SIZEOF_VOID_P EQUAL 4)
message(FATAL_ERROR "32-bit support is currently unsupported, check back with a later version of HipHop")
ENDIF()
if ("$ENV{USE_HHVM}" STREQUAL "1")
message("Building for HHVM")
endif()
if ("$ENV{USE_HPHPC}" STREQUAL "1")
message(FATAL_ERROR "Building HPHPc is no longer supported")
endif()
+13 -13
Ver Arquivo
@@ -1,46 +1,46 @@
# HipHop VM for PHP [![Build Status](https://travis-ci.org/facebook/hiphop-php.png?branch=master)](https://travis-ci.org/facebook/hiphop-php)
# HHVM [![Build Status](https://travis-ci.org/facebook/hhvm.png?branch=master)](https://travis-ci.org/facebook/hhvm)
HipHop VM (HHVM) is a new open-source virtual machine designed for executing programs written in PHP. HHVM uses a just-in-time compilation approach to achieve superior performance while maintaining the flexibility that PHP developers are accustomed to. HipHop VM (and before it HPHPc) has realized > 5x increase in throughput for Facebook compared with Zend PHP 5.2.
HHVM (aka the HipHop Virtual Machine) is a new open-source virtual machine designed for executing programs written in PHP. HHVM uses a just-in-time compilation approach to achieve superior performance while maintaining the flexibility that PHP developers are accustomed to. To date, HHVM (and its predecessor HPHPc before it) has realized over a 9x increase in web request throughput and over a 5x reduction in memory consumption for Facebook compared with the Zend PHP 5.2 engine + APC.
HipHop is most commonly run as a standalone server, replacing both Apache and modphp.
HHVM can be run as a standalone webserver (i.e. without the Apache webserver and the "modphp" extension). HHVM can also be used together with a FastCGI-based webserver, and work is in progress to make HHVM work smoothly with Apache.
## 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.
Our [FAQ](https://github.com/facebook/hhvm/wiki/FAQ) has answers to many common questions about HHVM, from [general questions](https://github.com/facebook/hhvm/wiki/FAQ#general) to questions geared towards those that want to [use](https://github.com/facebook/hhvm/wiki/FAQ#users) or [contribute](https://github.com/facebook/hhvm/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).
You can install a [prebuilt package](https://github.com/facebook/hhvm/wiki#installing-pre-built-packages-for-hhvm) or [compile from source](https://github.com/facebook/hhvm/wiki#building-hhvm).
## Running
You can run standalone programs just by passing them to hhvm: `hhvm my_script.php`.
HipHop bundles in a webserver. So if you want to run on port 80 in the current directory:
HHVM bundles in a webserver. So if you want to run on port 80 in the current directory:
```
sudo hhvm -m server
```
For anything more complicated, you'll want to make a [config.hdf](https://github.com/facebook/hiphop-php/wiki/Runtime-options#server) and run `sudo hhvm -m server -c config.hdf`.
For anything more complicated, you'll want to make a [config.hdf](https://github.com/facebook/hhvm/wiki/Runtime-options#server) and run `sudo hhvm -m server -c config.hdf`.
## Contributing
We'd love to have your help in making HipHop better.
We'd love to have your help in making HHVM 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.
Before changes can be accepted a [Contributor License Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hhvm/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 run into problems, please open an [issue](http://github.com/facebook/hhvm/issues), or better yet, [fork us and send a pull request](https://github.com/facebook/hhvm/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.
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.
All the open issues tagged [Zend incompatibility](https://github.com/facebook/hhvm/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/hhvm/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.
## License
HipHop VM is licensed under the PHP and Zend licenses except as otherwise noted.
HHVM 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.
See [Reporting Crashes](https://github.com/facebook/hhvm/wiki/Reporting-Crashes) for helpful tips on how to report crashes in an actionable manner.
-1
Ver Arquivo
@@ -1 +0,0 @@
This file just exists to keep the bin/ directory in git.
externo
+1 -1
Ver Arquivo
@@ -3,7 +3,7 @@
if [ "$1" = '--help' ] || [ "$1" = '-h' ]; then
echo 'usage: ./configure -Dvariable=argument ...\n'
echo 'Variables: '
echo ' CMAKE_BUILD_TYPE=Debug|Release Sets build type (default Relase).'
echo ' CMAKE_BUILD_TYPE=Debug|Release Sets build type (default Release).'
exit 2
fi
+30 -8
Ver Arquivo
@@ -1,6 +1,6 @@
#########################################
#
# Install all the dependancies for HipHop
# Install all the dependencies for HipHop
#
#########################################
@@ -20,12 +20,15 @@ if [ "x${TRAVIS}" != "x" ]; then
fi
export CMAKE_PREFIX_PATH=`/bin/pwd`/..
export HPHP_HOME=`/bin/pwd`
# install apt-fast to speedup later dependency installation
# install python-software-properties before trying to add a PPA
sudo apt-get -y update
sudo apt-get install -y python-software-properties
# install apt-fast to speed up later dependency installation
sudo add-apt-repository -y ppa:apt-fast/stable
sudo apt-get update
sudo apt-get install apt-fast
sudo apt-get -y update
sudo apt-get -y install apt-fast
# install the actual dependencies
sudo apt-fast -y update
@@ -33,8 +36,8 @@ 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 \
libboost-program-options1.48-dev libboost-filesystem1.48-dev libboost-thread1.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 &
@@ -43,6 +46,9 @@ 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 &
# init submodules
git submodule update --init
# wait until all background processes finished
FAIL=0
@@ -60,6 +66,22 @@ else
exit 100
fi
# Leave this install till after the main parallel package install above
# since it adds a non-12.04 package repo and we don't want to
# pull EVERYTHING in, just the newer gcc compiler (and toolchain)
GCC_VER=4.7
if [ "x${TRAVIS}" != "x" ]; then
GCC_VER=4.8
fi
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
sudo apt-get -y update
sudo apt-get -y install gcc-${GCC_VER} g++-${GCC_VER}
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_VER} 60 \
--slave /usr/bin/g++ g++ /usr/bin/g++-${GCC_VER}
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 40 \
--slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --set gcc /usr/bin/gcc-${GCC_VER}
# libevent
cd libevent
git checkout release-1.4.14b-stable
@@ -101,4 +123,4 @@ cmake .
echo "-------------------------------------------------------------------------"
echo "Done. Now run:"
echo " CMAKE_PREFIX_PATH=\`pwd\`/.. HPHP_HOME=\`pwd\` make"
echo " CMAKE_PREFIX_PATH=\`pwd\`/.. make"
+26
Ver Arquivo
@@ -0,0 +1,26 @@
# HHVM build results
*.hhbc
*.[oa]
/hhvm/hhvm
/hhvm/hphp
# vim swapfiles
.*.swp
.*.swo
# tags files
*/tags
*/TAGS
# logs
*.log
# git patch files
*.diff
# OS X
.DS_Store
._.DS_Store
# gdb
.gdb_history
+13 -50
Ver Arquivo
@@ -16,44 +16,12 @@
#
include(HPHPSetup)
include(FollySetup)
include(ExtZendCompat)
# HHVM Build
SET(USE_HHVM TRUE)
SET(ENV{HHVM} 1)
ADD_DEFINITIONS("-DHHVM -DHHVM_BINARY=1 -DHHVM_PATH=\\\"${HPHP_HOME}/hphp/hhvm/hhvm\\\"")
add_definitions("-DHHVM")
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})
auto_sources(files "*.c" "RECURSE" "${CMAKE_CURRENT_SOURCE_DIR}/${dir}")
list(APPEND C_SOURCES ${files})
auto_sources(files "*.S" "RECURSE" "${CMAKE_CURRENT_SOURCE_DIR}/${dir}")
list(APPEND ASM_SOURCES ${files})
endforeach(dir ${RECURSIVE_SOURCE_SUBDIRS})
if(NOT LINUX)
add_definitions(-DNO_HARDWARE_COUNTERS)
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")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
if (${file} MATCHES "/test/")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
endforeach(file ${CXX_SOURCES})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/bin")
add_subdirectory(tools/bootstrap)
add_subdirectory(third_party/libafdt)
add_subdirectory(third_party/libmbfl)
@@ -62,19 +30,11 @@ add_subdirectory(third_party/timelib)
add_subdirectory(third_party/lz4)
add_subdirectory(third_party/double-conversion)
add_subdirectory(third_party/folly)
ADD_LIBRARY(hphp_runtime_static STATIC
${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")
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(third_party/libzip)
if(ENABLE_FASTCGI)
add_subdirectory(third_party/ti)
add_subdirectory(third_party/thrift)
endif()
add_subdirectory(vixl)
add_subdirectory(neo)
@@ -82,11 +42,14 @@ add_subdirectory(parser)
add_subdirectory(zend)
add_subdirectory(util)
add_subdirectory(hhbbc)
add_subdirectory(compiler)
add_subdirectory(runtime)
add_subdirectory(runtime/ext_hhvm)
add_subdirectory(hhvm)
add_subdirectory(system)
add_subdirectory(hhvm)
if (NOT "$ENV{HPHP_NOTEST}" STREQUAL "1")
add_subdirectory(test)
endif ()
+102 -7
Ver Arquivo
@@ -1,9 +1,104 @@
Next release
- <cool stuff goes here>
- FrozenMap collection
- Deprecated Vector|Set|Map::put() method removed
- == between Frozen{Vector|Set|Map} and {Vector|Set|Map} now can return true
- Map collections learned the in-place retain() and retainWithKey()
- 'num' scalar typehint that accepts both ints and floats
"Beastie Boys" 6-Jan-2014
- Support lex-time binary constants (eg. 0b10111)
- StreamWrappers now support rmdir, mkdir, rename and unlink
- Miscellaneous Zend PHP compatibility fixes
- Default StatCache to off
- Miscellaneous FastCGI fixes
- Miscellaneous region compiler fixes
- Map and StableMap collections use the same underlying implementation
- Trait requirements enforced
- hhprof performance improvements
- Add array to string conversion notice
- Add RaiseNotice IR opcode
- Fix VirtualHost.<name>.Pattern matching
- Fix various memory leaks (pdo_parse_params, Gen*WaitHandle)
- Import a lot more Zend tests that used to crash or hang
- Clean up base.h
- XLS register allocation cleanup
- Enable region compiler by default for JIT functions in ahot
- Fatal on eval() in RepoAuthoritative mode
- Enable LTO for HHVM
- Fix a few SPL compatibility issues
"Appleseed" 23-Dec-2013
- Fix issues with DOCUMENT_ROOT in fastcgi
- Better type inference for collections and builtins in repo mode
- Shorter syntax for lambda expressions w/ automatic captures
- Parser support for trait require clauses
- Move FrozenVector and Set to the HH namespace
- Fix resource to array conversion
- Fix a request local memory leak in foreach of apc arrays
- Initial php_odbc API implementation
- Implement PHP's hash_copy() function
- Experimental tool: Memoization Opportunity Profiler
- Various small parity/behavior fixes (in phar, proc_open, filter_var)
- A Eval.DumpHhas=1 option to dump hhas for a php file
- Better warnings in Set::toArray
- Fix the behavior of foreach loops in finally blocks
- chmod -x runtime/vm/jit/*.{cpp,h}
- Changes to make hhvm build clean with clang-3.4
- Fix array_product to not be bug-compatible with PHP 5.2
- Change the Map datastructure---preserves order and does faster foreach
- FrozenSet collection
- Generate pid.map when we unmap text section, for the perf tool
- Implemented GlobIterator
- Implemented Reflection::export and Reflection::getModifierNames
"Tom Yum" 9-Dec-2013
- support date.timezone in ini files
- implement fileinfo
- special comparisons for DateTime
- delete unimplemented functions
- support for the finally clause in try blocks
"Huarache" 26-Nov-2013
- Linker re-ordering of hot functions
- Huge pages for hot functions
- Implement ZipArchive
- preg_replace /e support
- get_mem_usage() no longer can be negative
- Userland file system support
- Implement fileinfo extension
- wordwrap() fixes
- PDO::sqliteCreateFunction()
- Implement NumberFormatter
- Implement Locale
- Implement DatePeriod
- Many reflection fixes
- Stub out PharData
- A ton of performance fixes
- A ton of open source framework fixes
- FastCGI Server Support
"Garlic Alfredo" 11-Nov-2013
- teach implode() about collections
- fix ini parsing leak
- Make array not an instanceof Traversable
"Burrito" 28-Oct-2013
- Initial support for using FastCGI
- Initial support for php.ini configuration files
- Log when a nullable (e.g. ?int) is incorrect
- Add support for collections to array_diff, array_diff_key, array_intersect,
array_intersect_key
- tc-print improvements and fixes
- Several debugger fixes
- More improvements to the experimental PHP extension compat layer
- Fixed how parse errors are handled by eval()
- Support custom reason for status header
- Emit better error message when hhvm's systemlib doesn't load properly
- Fixes / clarifications added to the bytecode specification
- Lots of other bug fixes, clean up, PHP compat fixes, and JIT improvements
"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()
- Direct invocation of callable arrays: $f = [$cls_or_obj, 'method']; $f()
- ASAN clean
- Support dynamically loadable extensions
- Support loading mini-systemlibs from extensions
@@ -25,7 +120,7 @@ Next release
- Support arbitrary expressions inside empty()
"Bobotie" 16-Sep-2013
- HNI (HipHop Native Interface) for calling C++ functions from Php
- 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.
@@ -39,14 +134,14 @@ Next release
- Import ftp extension
"Kimchi" 2-Sep-2013
- Fix order of custom attributes and visibility in ctor arg promotion
- 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
- Improve hhvm command line 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
@@ -104,7 +199,7 @@ Next release
"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
- Consolidate ObjectData and Instance
- Prototype heap tracing framework & Heap profiler
- Better JIT code generation for Mod and Div
- Fixes to enable compilation with clang
+16 -14
Ver Arquivo
@@ -66,7 +66,7 @@
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/parser/location.h"
@@ -1927,6 +1927,7 @@ StatementPtr AliasManager::canonicalizeRecur(StatementPtr s, int &ret) {
switch (stype) {
case Statement::KindOfUseTraitStatement:
case Statement::KindOfTraitRequireStatement:
case Statement::KindOfTraitPrecStatement:
case Statement::KindOfTraitAliasStatement:
return StatementPtr();
@@ -1968,7 +1969,7 @@ StatementPtr AliasManager::canonicalizeRecur(StatementPtr s, int &ret) {
}
case Statement::KindOfIfBranchStatement:
always_assert(0);
always_assert(false);
break;
case Statement::KindOfForStatement: {
@@ -2108,7 +2109,6 @@ int AliasManager::collectAliasInfoRecur(ConstructPtr cs, bool unused) {
}
cs->clearVisited();
cs->clearChildOfYield();
StatementPtr s = dpc(Statement, cs);
if (s) {
@@ -2361,9 +2361,6 @@ int AliasManager::collectAliasInfoRecur(ConstructPtr cs, bool unused) {
case Expression::KindOfSimpleFunctionCall:
{
SimpleFunctionCallPtr sfc(spc(SimpleFunctionCall, e));
if (sfc->getName() == "hphp_create_continuation") {
m_inlineAsExpr = false;
}
sfc->updateVtFlags();
}
case Expression::KindOfDynamicFunctionCall:
@@ -2399,9 +2396,6 @@ 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) {
@@ -2537,8 +2531,10 @@ public:
}
private:
#define CONSTRUCT_PARAMS(from) \
#define CONSTRUCT_EXP(from) \
(from)->getScope(), (from)->getLocation()
#define CONSTRUCT_STMT(from) \
(from)->getScope(), (from)->getLabelScope(), (from)->getLocation()
AnalysisResultConstPtr m_ar;
bool m_changed;
@@ -2611,7 +2607,7 @@ private:
ExpressionListPtr el(
new ExpressionList(
CONSTRUCT_PARAMS(target),
CONSTRUCT_EXP(target),
ExpressionList::ListKindComma));
if (target->isUnused()) {
el->setUnused(true);
@@ -2955,7 +2951,7 @@ private:
slistPtr->insertElement(
ExpStatementPtr(
new ExpStatement(
CONSTRUCT_PARAMS(slistPtr), assertion)),
CONSTRUCT_STMT(slistPtr), assertion)),
idx);
}
break;
@@ -3036,12 +3032,12 @@ private:
} else {
ExpStatementPtr newExpStmt(
new ExpStatement(
CONSTRUCT_PARAMS(branch),
CONSTRUCT_STMT(branch),
after));
IfBranchStatementPtr newBranch(
new IfBranchStatement(
CONSTRUCT_PARAMS(branch),
CONSTRUCT_STMT(branch),
ExpressionPtr(), newExpStmt));
branches->addElement(newBranch);
@@ -3308,6 +3304,12 @@ private:
static bool isNewResult(ExpressionPtr e) {
if (!e) return false;
if (e->is(Expression::KindOfNewObjectExpression)) return true;
if (e->is(Expression::KindOfBinaryOpExpression)) {
auto b = spc(BinaryOpExpression, e);
if (b->getOp() == T_COLLECTION) {
return true;
}
}
if (e->is(Expression::KindOfAssignmentExpression)) {
return isNewResult(spc(AssignmentExpression, e)->getValue());
}
+74 -66
Ver Arquivo
@@ -32,6 +32,7 @@
#include "hphp/compiler/statement/loop_statement.h"
#include "hphp/compiler/statement/class_variable.h"
#include "hphp/compiler/statement/use_trait_statement.h"
#include "hphp/compiler/statement/trait_require_statement.h"
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/package.h"
#include "hphp/compiler/parser/parser.h"
@@ -488,8 +489,7 @@ void AnalysisResult::link(FileScopePtr user, FileScopePtr provider) {
bool AnalysisResult::addClassDependency(FileScopePtr usingFile,
const std::string &className) {
if (BuiltinSymbols::s_classes.find(className) !=
BuiltinSymbols::s_classes.end())
if (m_systemClasses.find(className) != m_systemClasses.end())
return true;
StringToClassScopePtrVecMap::const_iterator iter =
@@ -507,8 +507,7 @@ bool AnalysisResult::addClassDependency(FileScopePtr usingFile,
bool AnalysisResult::addFunctionDependency(FileScopePtr usingFile,
const std::string &functionName) {
if (BuiltinSymbols::s_functions.find(functionName) !=
BuiltinSymbols::s_functions.end())
if (m_functions.find(functionName) != m_functions.end())
return true;
StringToFunctionScopePtrMap::const_iterator iter =
m_functionDecs.find(functionName);
@@ -570,12 +569,16 @@ bool AnalysisResult::isSystemConstant(const std::string &constName) const {
///////////////////////////////////////////////////////////////////////////////
// Program
void AnalysisResult::loadBuiltins() {
AnalysisResultPtr ar = shared_from_this();
BuiltinSymbols::LoadFunctions(ar, m_functions);
BuiltinSymbols::LoadClasses(ar, m_systemClasses);
BuiltinSymbols::LoadVariables(ar, m_variables);
BuiltinSymbols::LoadConstants(ar, m_constants);
void AnalysisResult::addSystemFunction(FunctionScopeRawPtr fs) {
FunctionScopePtr& entry = m_functions[fs->getName()];
assert(!entry);
entry = fs;
}
void AnalysisResult::addSystemClass(ClassScopeRawPtr cs) {
ClassScopePtr& entry = m_systemClasses[cs->getName()];
assert(!entry);
entry = cs;
}
void AnalysisResult::checkClassDerivations() {
@@ -587,7 +590,11 @@ void AnalysisResult::checkClassDerivations() {
hphp_string_iset seen;
cls->checkDerivation(ar, seen);
if (Option::WholeProgram) {
cls->importUsedTraits(ar);
try {
cls->importUsedTraits(ar);
} catch (const AnalysisTimeFatalException& e) {
cls->setFatal(e);
}
}
}
}
@@ -605,22 +612,26 @@ void AnalysisResult::resolveNSFallbackFuncs() {
}
void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
const StringToFunctionScopePtrMap &funcs = fs->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter = funcs.begin();
iter != funcs.end(); ++iter) {
FunctionScopePtr func = iter->second;
for (const auto& iter : fs->getFunctions()) {
FunctionScopePtr func = iter.second;
if (!func->inPseudoMain()) {
FunctionScopePtr &funcDec = m_functionDecs[iter->first];
FunctionScopePtr &funcDec = m_functionDecs[iter.first];
if (funcDec) {
FunctionScopePtrVec &funcVec = m_functionReDecs[iter->first];
int sz = funcVec.size();
if (!sz) {
funcDec->setRedeclaring(sz++);
funcVec.push_back(funcDec);
if (funcDec->isSystem()) {
assert(funcDec->allowOverride());
funcDec = func;
} else if (func->isSystem()) {
assert(func->allowOverride());
} else {
FunctionScopePtrVec &funcVec = m_functionReDecs[iter.first];
int sz = funcVec.size();
if (!sz) {
funcDec->setRedeclaring(sz++);
funcVec.push_back(funcDec);
}
func->setRedeclaring(sz++);
funcVec.push_back(func);
}
func->setRedeclaring(sz++);
funcVec.push_back(func);
} else {
funcDec = func;
}
@@ -628,13 +639,12 @@ void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
}
if (const StringToFunctionScopePtrVecMap *redec = fs->getRedecFunctions()) {
for (StringToFunctionScopePtrVecMap::const_iterator iter = redec->begin();
iter != redec->end(); ++iter) {
FunctionScopePtrVec::const_iterator i = iter->second.begin();
FunctionScopePtrVec::const_iterator e = iter->second.end();
FunctionScopePtr &funcDec = m_functionDecs[iter->first];
for (const auto &iter : *redec) {
FunctionScopePtrVec::const_iterator i = iter.second.begin();
FunctionScopePtrVec::const_iterator e = iter.second.end();
FunctionScopePtr &funcDec = m_functionDecs[iter.first];
assert(funcDec); // because the first one was in funcs above
FunctionScopePtrVec &funcVec = m_functionReDecs[iter->first];
FunctionScopePtrVec &funcVec = m_functionReDecs[iter.first];
int sz = funcVec.size();
if (!sz) {
funcDec->setRedeclaring(sz++);
@@ -647,11 +657,9 @@ void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
}
}
const StringToClassScopePtrVecMap &classes = fs->getClasses();
for (StringToClassScopePtrVecMap::const_iterator iter = classes.begin();
iter != classes.end(); ++iter) {
ClassScopePtrVec &clsVec = m_classDecs[iter->first];
clsVec.insert(clsVec.end(), iter->second.begin(), iter->second.end());
for (const auto& iter : fs->getClasses()) {
ClassScopePtrVec &clsVec = m_classDecs[iter.first];
clsVec.insert(clsVec.end(), iter.second.begin(), iter.second.end());
}
m_classAliases.insert(fs->getClassAliases().begin(),
@@ -967,11 +975,14 @@ struct OptVisitor {
AnalysisResultPtr m_ar;
unsigned m_nscope;
JobQueueDispatcher<BlockScope *, OptWorker<When> > *m_dispatcher;
JobQueueDispatcher<OptWorker<When>> *m_dispatcher;
};
template <typename When>
class OptWorker : public JobQueueWorker<BlockScope *, true, true> {
class OptWorker : public JobQueueWorker<BlockScope*,
void*,
true,
true> {
public:
OptWorker() {}
@@ -990,8 +1001,8 @@ public:
acc->second += 1;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
try {
DepthFirstVisitor<When, OptVisitor > *visitor =
(DepthFirstVisitor<When, OptVisitor >*)m_opaque;
auto visitor =
(DepthFirstVisitor<When, OptVisitor>*) m_context;
{
Lock ldep(BlockScope::s_depsMutex);
Lock lstate(BlockScope::s_jobStateMutex);
@@ -1180,7 +1191,7 @@ void OptWorker<Pre>::onThreadExit() {
} \
if (threadCount <= 0) threadCount = 1; \
this->m_data.m_dispatcher = \
new JobQueueDispatcher<BlockScope *, worker >( \
new JobQueueDispatcher<worker>( \
threadCount, true, 0, false, this); \
} while (0)
@@ -1225,7 +1236,7 @@ template <typename When>
void
AnalysisResult::preWaitCallback(bool first,
const BlockScopeRawPtrQueue &scopes,
void *opaque) {
void *context) {
// default is no-op
}
@@ -1234,7 +1245,7 @@ bool
AnalysisResult::postWaitCallback(bool first,
bool again,
const BlockScopeRawPtrQueue &scopes,
void *opaque) {
void *context) {
// default is no-op
return again;
}
@@ -1299,7 +1310,7 @@ struct BIPairCmp {
template <typename When>
void
AnalysisResult::processScopesParallel(const char *id,
void *opaque /* = NULL */) {
void *context /* = NULL */) {
BlockScopeRawPtrQueue scopes;
getScopesSet(scopes);
@@ -1336,7 +1347,7 @@ AnalysisResult::processScopesParallel(const char *id,
BlockScopeRawPtrQueue enqueued;
again = dfv.visitParallel(scopes, first, enqueued);
preWaitCallback<When>(first, scopes, opaque);
preWaitCallback<When>(first, scopes, context);
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
{
@@ -1390,7 +1401,7 @@ AnalysisResult::processScopesParallel(const char *id,
std::cout << "Number of waiting scopes: " << numWaiting << std::endl;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
again = postWaitCallback<When>(first, again, scopes, opaque);
again = postWaitCallback<When>(first, again, scopes, context);
first = false;
} while (again);
dfv.data().stop();
@@ -1562,7 +1573,8 @@ DepthFirstVisitor<InferTypes, OptVisitor>::visitScope(BlockScopeRawPtr scope) {
template<>
bool AnalysisResult::postWaitCallback<InferTypes>(
bool first, bool again, const BlockScopeRawPtrQueue &scopes, void *opaque) {
bool first, bool again,
const BlockScopeRawPtrQueue &scopes, void *context) {
#ifdef HPHP_INSTRUMENT_TYPE_INF
std::cout << "Number of rescheduled: " <<
@@ -1604,12 +1616,10 @@ void AnalysisResult::inferTypes() {
BlockScopeRawPtrQueue scopes;
getScopesSet(scopes);
for (BlockScopeRawPtrQueue::iterator
it = scopes.begin(), end = scopes.end();
it != end; ++it) {
(*it)->setInTypeInference(true);
(*it)->clearUpdated();
assert((*it)->getNumDepsToWaitFor() == 0);
for (auto scope : scopes) {
scope->setInTypeInference(true);
scope->clearUpdated();
assert(scope->getNumDepsToWaitFor() == 0);
}
#ifdef HPHP_INSTRUMENT_TYPE_INF
@@ -1620,13 +1630,11 @@ void AnalysisResult::inferTypes() {
processScopesParallel<InferTypes>("InferTypes");
for (BlockScopeRawPtrQueue::iterator
it = scopes.begin(), end = scopes.end();
it != end; ++it) {
(*it)->setInTypeInference(false);
(*it)->clearUpdated();
assert((*it)->getMark() == BlockScope::MarkProcessed);
assert((*it)->getNumDepsToWaitFor() == 0);
for (auto scope : scopes) {
scope->setInTypeInference(false);
scope->clearUpdated();
assert(scope->getMark() == BlockScope::MarkProcessed);
assert(scope->getNumDepsToWaitFor() == 0);
}
}
@@ -1668,12 +1676,12 @@ StatementPtr DepthFirstVisitor<Post, OptVisitor>::visit(StatementPtr stmt) {
return stmt->postOptimize(this->m_data.m_ar);
}
class FinalWorker : public JobQueueWorker<MethodStatementPtr> {
class FinalWorker : public JobQueueWorker<MethodStatementPtr, AnalysisResult*> {
public:
virtual void doJob(MethodStatementPtr m) {
try {
AliasManager am(1);
am.finalSetup(((AnalysisResult*)m_opaque)->shared_from_this(), m);
am.finalSetup(m_context->shared_from_this(), m);
} catch (Exception &e) {
Logger::Error("%s", e.getMessage().c_str());
}
@@ -1682,11 +1690,11 @@ public:
template<>
void AnalysisResult::preWaitCallback<Post>(
bool first, const BlockScopeRawPtrQueue &scopes, void *opaque) {
assert(!Option::ControlFlow || opaque != nullptr);
bool first, const BlockScopeRawPtrQueue &scopes, void *context) {
assert(!Option::ControlFlow || context != nullptr);
if (first && Option::ControlFlow) {
JobQueueDispatcher<FinalWorker::JobType, FinalWorker> *dispatcher
= (JobQueueDispatcher<FinalWorker::JobType, FinalWorker> *) opaque;
auto *dispatcher
= (JobQueueDispatcher<FinalWorker> *) context;
for (BlockScopeRawPtrQueue::const_iterator it = scopes.begin(),
end = scopes.end(); it != end; ++it) {
BlockScopeRawPtr scope = *it;
@@ -1710,7 +1718,7 @@ void AnalysisResult::postOptimize() {
}
if (threadCount <= 0) threadCount = 1;
JobQueueDispatcher<FinalWorker::JobType, FinalWorker> dispatcher(
JobQueueDispatcher<FinalWorker> dispatcher(
threadCount, true, 0, false, this);
processScopesParallel<Post>("PostOptimize", &dispatcher);
+4 -2
Ver Arquivo
@@ -24,6 +24,7 @@
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/analysis/function_container.h"
#include "hphp/compiler/package.h"
#include "hphp/compiler/hphp.h"
#include "hphp/util/string-bag.h"
#include "hphp/util/thread-local.h"
@@ -36,7 +37,7 @@ namespace HPHP {
DECLARE_BOOST_TYPES(ClassScope);
DECLARE_BOOST_TYPES(FileScope);
DECLARE_EXTENDED_BOOST_TYPES(FileScope);
DECLARE_BOOST_TYPES(FunctionScope);
DECLARE_BOOST_TYPES(Location);
DECLARE_BOOST_TYPES(AnalysisResult);
@@ -150,7 +151,8 @@ public:
void addNSFallbackFunc(ConstructPtr c, FileScopePtr fs);
void loadBuiltins();
void addSystemFunction(FunctionScopeRawPtr fs);
void addSystemClass(ClassScopeRawPtr cs);
void analyzeProgram(bool system = false);
void analyzeIncludes();
void analyzeProgramFinal();
+1 -3
Ver Arquivo
@@ -155,9 +155,7 @@ bool BlockScope::hasUser(BlockScopeRawPtr user, int useKinds) const {
}
void BlockScope::addUse(BlockScopeRawPtr user, int useKinds) {
if (is(ClassScope) ? static_cast<HPHP::ClassScope*>(this)->isUserClass() :
is(FunctionScope) &&
static_cast<HPHP::FunctionScope*>(this)->isUserFunction()) {
if ((is(ClassScope) || is(FunctionScope)) && getStmt()) {
if (user.get() == this) {
m_selfUser |= useKinds;
+391
Ver Arquivo
@@ -0,0 +1,391 @@
/*
+----------------------------------------------------------------------+
| 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/analysis/capture_extractor.h"
#include "hphp/compiler/expression/join_clause.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/parser/hphp.tab.hpp"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
/**
* Rewrites the construct rooted in cp so that it is in a form
* that a query processor can evaluate while referencing only
* state that is contained in the query processor or supplied
* to the query processor in the form of arguments to the query.
* For instance, a reference to a local variable in the scope
* containing the query expression will be rewritten into a
* reference to a (synthetic) parameter of the query expression.
* This is similar to the way lambda expressions capture variables
* from their enclosing environment.
* Note that rewriting implies allocating new objects.
* The original construct is not mutated in any way.
* If the original construct is already in the right form, it is
* returned as is.
*/
ExpressionPtr CaptureExtractor::rewrite(ExpressionPtr ep) {
assert(ep != nullptr);
switch (ep->getKindOf()) {
case Expression::KindOfQueryExpression: {
return rewriteQuery(static_pointer_cast<QueryExpression>(ep));
}
case Expression::KindOfSelectClause: {
// leave select clauses alone, another visitor deals with them.
return ep;
}
case Expression::KindOfFromClause:
case Expression::KindOfLetClause:
case Expression::KindOfIntoClause:
case Expression::KindOfWhereClause: {
return rewriteSimpleClause(static_pointer_cast<SimpleQueryClause>(ep));
}
case Expression::KindOfGroupClause:
case Expression::KindOfJoinClause:
case Expression::KindOfOrderbyClause:
case Expression::KindOfOrdering: {
// leave these alone. they are query specific and not parameterizable.
return ep;
}
case Expression::KindOfObjectPropertyExpression: {
return rewriteObjectProperty(
static_pointer_cast<ObjectPropertyExpression>(ep));
}
case Expression::KindOfSimpleFunctionCall: {
return rewriteCall(static_pointer_cast<SimpleFunctionCall>(ep));
}
case Expression::KindOfScalarExpression: {
// Leave scalars alone. If the query processor can't handle them
// rewriting won't help.
return ep;
}
case Expression::KindOfUnaryOpExpression: {
return rewriteUnary(static_pointer_cast<UnaryOpExpression>(ep));
}
case Expression::KindOfBinaryOpExpression: {
return rewriteBinary(static_pointer_cast<BinaryOpExpression>(ep));
}
case Expression::KindOfSimpleVariable: {
return rewriteSimpleVariable(static_pointer_cast<SimpleVariable>(ep));
}
case Expression::KindOfExpressionList: {
return rewriteExpressionList(static_pointer_cast<ExpressionList>(ep));
}
default: {
// If we get here, the expression is not a candidate for evaluation
// by the query processor, so just turn it into a query parameter.
return newQueryParamRef(ep);
}
}
}
/**
* Appends the given expression to end of the m_capturedExpressions list
* and creates a new expression with the same scope and source location
* that represents a reference to a query parameter. Query parameters do
* not have a source code equivalent, but inform the query processor that
* this expression represents the ith argument value, where i is zero based
* and forms the last character of the special string @query_param_i.
*/
SimpleVariablePtr CaptureExtractor::newQueryParamRef(ExpressionPtr ae) {
assert(ae != nullptr);
char count = '0' + m_capturedExpressions.size();
std::string pname = "@query_param_";
pname.push_back(count);
SimpleVariablePtr param(
new SimpleVariable(ae->getScope(), ae->getLocation(), pname)
);
m_capturedExpressions.push_back(ae);
return param;
}
/**
* If one or more of the arguments of the function call depend on query only
* state (query local but not a query parameter reference), then rewrite
* all of the arguments to be query local and return the rewritten
* function call (the query processor has to either figure out a way to call
* the function or must cause a runtime error when faced with the call).
* Otherwise, rewrite the call as a query parameter reference.
*/
ExpressionPtr CaptureExtractor::rewriteCall(SimpleFunctionCallPtr sfc) {
assert(sfc != nullptr);
if (sfc->hadBackslash() ||
(sfc->getClass() != nullptr && !sfc->getClassName().empty())) {
return newQueryParamRef(sfc);
}
auto args = sfc->getParams();
auto pc = args == nullptr ? 0 : args->getCount();
bool isQueryCall = false;
for (int i = 0; i < pc; i++) {
auto arg = (*args)[i];
assert(arg != nullptr);
isQueryCall |= this->dependsOnQueryOnlyState(arg);
}
if (!isQueryCall) return newQueryParamRef(sfc);
ExpressionListPtr newArgs(
new ExpressionList(args->getScope(), args->getLocation())
);
bool noRewrites = true;
for (int i = 0; i < pc; i++) {
auto arg = (*args)[i];
auto newArg = rewrite(arg);
if (arg != newArg) noRewrites = false;
newArgs->addElement(newArg);
}
if (noRewrites) return sfc;
SimpleFunctionCallPtr result(
new SimpleFunctionCall(sfc->getScope(), sfc->getLocation(),
sfc->getName(), false, newArgs, ExpressionPtr())
);
return result;
}
/**
* Traverses the expression tree rooted at e and returns true if
* any node in the tree is a simple variable that references a
* name in m_boundVars.
*/
bool CaptureExtractor::dependsOnQueryOnlyState(ExpressionPtr e) {
assert(e != nullptr);
if (e->getKindOf() == Expression::KindOfSimpleVariable) {
auto sv = static_pointer_cast<SimpleVariable>(e);
auto varName = sv->getName();
for (auto &boundVar : m_boundVars) {
if (varName == boundVar) return true;
}
return false;
}
auto numKids = e->getKidCount();
for (int i = 0; i < numKids; i++) {
auto ei = e->getNthExpr(i);
if (ei == nullptr) return false; //Default param
if (dependsOnQueryOnlyState(ei)) return true;
}
return false;
}
/**
* If a simple variable refers to a name bound inside the query
* then leave it alone. If not, rewrite it to be reference to
* a query parameter.
*/
SimpleVariablePtr CaptureExtractor::rewriteSimpleVariable(
SimpleVariablePtr sv) {
assert(sv != nullptr);
auto varName = sv->getName();
for (auto &boundVar : m_boundVars) {
if (varName == boundVar) return sv;
}
return newQueryParamRef(sv);
}
/**
* Query expressions introduce a local scope with names introduced
* by some of the clauses of the query expression. This needs
* special handling so that we can track variables local to the query.
*/
QueryExpressionPtr CaptureExtractor::rewriteQuery(QueryExpressionPtr qe) {
assert(qe != nullptr);
auto clauses = qe->getClauses();
auto newClauses = rewriteExpressionList(clauses);
if (clauses == newClauses) return qe;
QueryExpressionPtr result(
new QueryExpression(qe->getScope(), qe->getLocation(), newClauses)
);
return result;
}
/**
* Rewrites any expression query clauses in this list of clauses, taking care
* to track variables local to the query.
*/
ExpressionListPtr CaptureExtractor::rewriteExpressionList(ExpressionListPtr l) {
int np = 0;
int nc = l->getCount();
ExpressionListPtr newList(
new ExpressionList(l->getScope(), l->getLocation())
);
bool noRewrites = true;
for (int i = 0; i < nc; i++) {
auto e = (*l)[i];
assert(e != nullptr);
auto kind = e->getKindOf();
switch (kind) {
case Expression::KindOfIntoClause: {
// The into expression is in the scope of the into clause
SimpleQueryClausePtr qcp(static_pointer_cast<SimpleQueryClause>(e));
m_boundVars.push_back(qcp->getIdentifier());
np++;
break;
}
case Expression::KindOfJoinClause: {
JoinClausePtr jcp(static_pointer_cast<JoinClause>(e));
m_boundVars.push_back(jcp->getVar());
np++;
break;
}
default:
break;
}
auto ne = rewrite(e);
if (ne != e) noRewrites = false;
newList->addElement(ne);
// deal with clauses that introduce names for subsequent clauses
switch (kind) {
case Expression::KindOfFromClause:
case Expression::KindOfLetClause: {
SimpleQueryClausePtr qcp(static_pointer_cast<SimpleQueryClause>(e));
m_boundVars.push_back(qcp->getIdentifier());
np++;
break;
}
case Expression::KindOfJoinClause: {
JoinClausePtr jcp(static_pointer_cast<JoinClause>(e));
auto groupId = jcp->getGroup();
if (!groupId.empty()) {
m_boundVars.push_back(groupId);
np++;
}
break;
}
default:
break;
}
}
while (np-- > 0) m_boundVars.pop_back();
if (noRewrites) return l;
return newList;
}
/*
* If the expression of a simple query clause is query local, then
* return the clause as is. Otherwise return a clone of the clause
* with the expression rewritten to reference a query parameter.
*/
SimpleQueryClausePtr CaptureExtractor::rewriteSimpleClause(
SimpleQueryClausePtr sc) {
assert (sc != nullptr);
auto expr = sc->getExpression();
auto newExpr = rewrite(expr);
if (expr == newExpr) return sc;
auto rsc = static_pointer_cast<SimpleQueryClause>(sc->clone());
rsc->setExpression(newExpr);
return rsc;
}
/*
* If the object expression is query local, that is, if it is a simple variable
* referring to a name declared in a query clause, or itself a query local
* object expression, then if keep this expression as is. If not, then
* rewrite this expression into a query parameter reference.
*/
ExpressionPtr CaptureExtractor::rewriteObjectProperty(
ObjectPropertyExpressionPtr ope) {
assert(ope != nullptr);
auto obj = ope->getObject();
if (this->dependsOnQueryOnlyState(obj)) {
auto prop = ope->getProperty();
if (prop->getKindOf() == Expression::KindOfScalarExpression) {
auto scalar = static_pointer_cast<ScalarExpression>(prop);
const string &propName = scalar->getLiteralString();
if (!propName.empty()) {
return ope;
}
}
}
return newQueryParamRef(ope);
}
/**
* If the unary operation is not PHP specific, but something a query
* processor can handle (+ - ! ~), then rewrite the operand to something
* the query processor can evaluate (such as a query parameter reference)
* and rewrite the entire expression to use the rewritten operand.
* If the rewritten operand is the same as the original operand, just
* return the expression as is.
*/
ExpressionPtr CaptureExtractor::rewriteUnary(UnaryOpExpressionPtr ue) {
assert (ue != nullptr);
if (!ue->getFront()) return nullptr;
switch (ue->getOp()) {
case '+':
case '-':
case '!':
case '~':
break; // Could be something the query processor can handle
default:
return newQueryParamRef(ue);
}
auto expr = ue->getExpression();
auto newExpr = rewrite(expr);
if (expr == newExpr) return ue;
UnaryOpExpressionPtr result(
new UnaryOpExpression(ue->getScope(), ue->getLocation(),
newExpr, ue->getOp(), true)
);
return result;
}
/**
* If the binary operation is not PHP specific, but something a query
* processor can handle (+ - * and so on), then rewrite the operands to
* something the query processor can evaluate (such as a query parameter
* references) and rewrite the entire expression to use the rewritten operands.
* If the rewritten operands are the same as the original operands, just
* return the expression as is.
*/
ExpressionPtr CaptureExtractor::rewriteBinary(BinaryOpExpressionPtr be) {
assert(be != nullptr);
switch (be->getOp()) {
case '+':
case '-':
case '*':
case '/':
case '%':
case '&':
case '|':
case '^':
case T_IS_IDENTICAL:
case T_IS_EQUAL:
case '>':
case '<':
case T_IS_GREATER_OR_EQUAL:
case T_IS_SMALLER_OR_EQUAL:
case T_IS_NOT_IDENTICAL:
case T_IS_NOT_EQUAL:
case T_BOOLEAN_OR:
case T_BOOLEAN_AND:
case T_LOGICAL_OR:
case T_LOGICAL_AND:
case '.':
break; // Could be something the query processor can handle
default:
return newQueryParamRef(be);
}
auto expr1 = be->getExp1();
auto expr2 = be->getExp2();
auto newExpr1 = rewrite(expr1);
auto newExpr2 = rewrite(expr2);
if (expr1 == newExpr1 && expr2 == newExpr2) return be;
BinaryOpExpressionPtr result(
new BinaryOpExpression(be->getScope(), be->getLocation(),
newExpr1, newExpr2, be->getOp())
);
return result;
}
}
+66
Ver Arquivo
@@ -0,0 +1,66 @@
/*
+----------------------------------------------------------------------+
| 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_CAPTURE_EXTRACTOR_H_
#define incl_HPHP_CAPTURE_EXTRACTOR_H_
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/query_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/simple_query_clause.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/expression/unary_op_expression.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
/** A rewriter for query expressions that capture variables that lie
* outside of the scope of the query expression. Subexpressions that
* contain such references are turned into references to query parameter
* variables. The original expressions are collected into the list
* returned by getCapturedEpressions. Their runtime values are obtained
* before the query is evaluated and are passed as arguments to the query
* processor.
*/
class CaptureExtractor {
public:
ExpressionPtr rewrite(ExpressionPtr ep);
std::vector<ExpressionPtr> getCapturedExpressions() {
return m_capturedExpressions;
}
private:
bool dependsOnQueryOnlyState(ExpressionPtr e);
SimpleVariablePtr newQueryParamRef(ExpressionPtr ae);
ExpressionPtr rewriteBinary(BinaryOpExpressionPtr be);
ExpressionPtr rewriteCall(SimpleFunctionCallPtr sfc);
ExpressionListPtr rewriteExpressionList(ExpressionListPtr l);
ExpressionPtr rewriteObjectProperty(ObjectPropertyExpressionPtr ope);
QueryExpressionPtr rewriteQuery(QueryExpressionPtr qe);
SimpleQueryClausePtr rewriteSimpleClause(SimpleQueryClausePtr sc);
SimpleVariablePtr rewriteSimpleVariable(SimpleVariablePtr sv);
ExpressionPtr rewriteUnary(UnaryOpExpressionPtr ue);
std::vector<ExpressionPtr> m_capturedExpressions;
std::vector<std::string> m_boundVars;
};
}
#endif // incl_HPHP_CAPTURE_EXTRACTOR_H_
+129 -21
Ver Arquivo
@@ -39,6 +39,7 @@
#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_require_statement.h"
#include "hphp/compiler/statement/trait_prec_statement.h"
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/runtime/base/zend-string.h"
@@ -473,6 +474,17 @@ void ClassScope::addImportTraitMethod(const TraitMethod &traitMethod,
m_importMethToTraitMap[methName].push_back(traitMethod);
}
void ClassScope::addTraitRequirement(const string &requiredName,
bool isExtends) {
assert(isTrait());
if (isExtends) {
m_traitRequiredExtends.insert(requiredName);
} else {
m_traitRequiredImplements.insert(requiredName);
}
}
void
ClassScope::setImportTraitMethodModifiers(const string &methName,
ClassScopePtr traitCls,
@@ -533,6 +545,7 @@ ClassScope::findTraitMethod(AnalysisResultPtr ar,
void ClassScope::findTraitMethodsToImport(AnalysisResultPtr ar,
ClassScopePtr trait) {
assert(Option::WholeProgram);
ClassStatementPtr tStmt =
dynamic_pointer_cast<ClassStatement>(trait->getStmt());
StatementListPtr tStmts = tStmt->getStmts();
@@ -549,7 +562,45 @@ void ClassScope::findTraitMethodsToImport(AnalysisResultPtr ar,
}
}
void ClassScope::importTraitRequirements(AnalysisResultPtr ar,
ClassScopePtr trait) {
if (isTrait()) {
for (auto const& req : trait->getTraitRequiredExtends()) {
addTraitRequirement(req, true);
}
for (auto const& req : trait->getTraitRequiredImplements()) {
addTraitRequirement(req, false);
}
} else {
for (auto const& req : trait->getTraitRequiredExtends()) {
if (!derivesFrom(ar, req, true, false)) {
getStmt()->analysisTimeFatal(
Compiler::InvalidDerivation,
Strings::TRAIT_REQ_EXTENDS,
m_originalName.c_str(),
req.c_str(),
trait->getOriginalName().c_str(),
"use"
);
}
}
for (auto const& req : trait->getTraitRequiredImplements()) {
if (!derivesFrom(ar, req, true, false)) {
getStmt()->analysisTimeFatal(
Compiler::InvalidDerivation,
Strings::TRAIT_REQ_IMPLEMENTS,
m_originalName.c_str(),
req.c_str(),
trait->getOriginalName().c_str(),
"use"
);
}
}
}
}
void ClassScope::applyTraitPrecRule(TraitPrecStatementPtr stmt) {
assert(Option::WholeProgram);
const string methodName = Util::toLower(stmt->getMethodName());
const string selectedTraitName = Util::toLower(stmt->getTraitName());
std::set<string> otherTraitNames;
@@ -580,12 +631,20 @@ void ClassScope::applyTraitPrecRule(TraitPrecStatementPtr stmt) {
// Report error if didn't find the selected trait
if (!foundSelectedTrait) {
Compiler::Error(Compiler::UnknownTrait, stmt);
stmt->analysisTimeFatal(
Compiler::UnknownTrait,
Strings::TRAITS_UNKNOWN_TRAIT,
selectedTraitName.c_str()
);
}
// Sanity checking: otherTraitNames should be empty now
if (otherTraitNames.size()) {
Compiler::Error(Compiler::UnknownTrait, stmt);
stmt->analysisTimeFatal(
Compiler::UnknownTrait,
Strings::TRAITS_UNKNOWN_TRAIT,
selectedTraitName.c_str()
);
}
}
@@ -596,6 +655,7 @@ bool ClassScope::hasMethod(const string &methodName) const {
ClassScopePtr
ClassScope::findSingleTraitWithMethod(AnalysisResultPtr ar,
const string &methodName) const {
assert(Option::WholeProgram);
ClassScopePtr trait = ClassScopePtr();
for (unsigned i = 0; i < m_usedTraitNames.size(); i++) {
@@ -613,6 +673,7 @@ ClassScope::findSingleTraitWithMethod(AnalysisResultPtr ar,
}
void ClassScope::addTraitAlias(TraitAliasStatementPtr aliasStmt) {
assert(Option::WholeProgram);
const string &traitName = aliasStmt->getTraitName();
const string &origMethName = aliasStmt->getMethodName();
const string &newMethName = aliasStmt->getNewMethodName();
@@ -623,6 +684,7 @@ void ClassScope::addTraitAlias(TraitAliasStatementPtr aliasStmt) {
void ClassScope::applyTraitAliasRule(AnalysisResultPtr ar,
TraitAliasStatementPtr stmt) {
assert(Option::WholeProgram);
const string traitName = Util::toLower(stmt->getTraitName());
const string origMethName = Util::toLower(stmt->getMethodName());
const string newMethName = Util::toLower(stmt->getNewMethodName());
@@ -635,8 +697,11 @@ void ClassScope::applyTraitAliasRule(AnalysisResultPtr ar,
traitCls = ar->findClass(traitName);
}
if (!traitCls || !(traitCls->isTrait())) {
Compiler::Error(Compiler::UnknownTrait, stmt);
return;
stmt->analysisTimeFatal(
Compiler::UnknownTrait,
Strings::TRAITS_UNKNOWN_TRAIT,
traitName.empty() ? origMethName.c_str() : traitName.c_str()
);
}
// Keep record of alias rule
@@ -647,8 +712,10 @@ void ClassScope::applyTraitAliasRule(AnalysisResultPtr ar,
MethodStatementPtr methStmt = findTraitMethod(ar, traitCls, origMethName,
visitedTraits);
if (!methStmt) {
Compiler::Error(Compiler::UnknownTraitMethod, stmt);
return;
stmt->analysisTimeFatal(
Compiler::UnknownTraitMethod,
Strings::TRAITS_UNKNOWN_TRAIT_METHOD, origMethName.c_str()
);
}
if (origMethName == newMethName) {
@@ -663,6 +730,7 @@ void ClassScope::applyTraitAliasRule(AnalysisResultPtr ar,
}
void ClassScope::applyTraitRules(AnalysisResultPtr ar) {
assert(Option::WholeProgram);
ClassStatementPtr classStmt = dynamic_pointer_cast<ClassStatement>(getStmt());
assert(classStmt);
StatementListPtr stmts = classStmt->getStmts();
@@ -695,6 +763,7 @@ void ClassScope::applyTraitRules(AnalysisResultPtr ar) {
// 1) implemented by other traits
// 2) duplicate
void ClassScope::removeSpareTraitAbstractMethods(AnalysisResultPtr ar) {
assert(Option::WholeProgram);
for (MethodToTraitListMap::iterator iter = m_importMethToTraitMap.begin();
iter != m_importMethToTraitMap.end(); iter++) {
@@ -732,9 +801,17 @@ void ClassScope::removeSpareTraitAbstractMethods(AnalysisResultPtr ar) {
}
void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
// Trait flattening is supposed to happen only when we have awareness of
// the whole program.
assert(Option::WholeProgram);
if (m_traitStatus == FLATTENED) return;
if (m_traitStatus == BEING_FLATTENED) {
Compiler::Error(Compiler::CyclicDependentTraits, getStmt());
getStmt()->analysisTimeFatal(
Compiler::CyclicDependentTraits,
"Cyclic dependency between traits involving %s",
getOriginalName().c_str()
);
return;
}
if (m_usedTraitNames.size() == 0) {
@@ -751,18 +828,53 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
}
}
if (isTrait()) {
for (auto const& req : getTraitRequiredExtends()) {
ClassScopePtr rCls = ar->findClass(req);
if (!rCls || rCls->isFinal() || rCls->isInterface()) {
getStmt()->analysisTimeFatal(
Compiler::InvalidDerivation,
Strings::TRAIT_BAD_REQ_EXTENDS,
m_originalName.c_str(),
req.c_str(),
req.c_str()
);
}
}
for (auto const& req : getTraitRequiredImplements()) {
ClassScopePtr rCls = ar->findClass(req);
if (!rCls || !(rCls->isInterface())) {
getStmt()->analysisTimeFatal(
Compiler::InvalidDerivation,
Strings::TRAIT_BAD_REQ_IMPLEMENTS,
m_originalName.c_str(),
req.c_str(),
req.c_str()
);
}
}
}
// Find trait methods to be imported
for (unsigned i = 0; i < m_usedTraitNames.size(); i++) {
ClassScopePtr tCls = ar->findClass(m_usedTraitNames[i]);
if (!tCls || !(tCls->isTrait())) {
setAttribute(UsesUnknownTrait);
Compiler::Error(Compiler::UnknownTrait, getStmt());
continue;
setAttribute(UsesUnknownTrait); // XXX: is this useful ... for anything?
getStmt()->analysisTimeFatal(
Compiler::UnknownTrait,
Strings::TRAITS_UNKNOWN_TRAIT,
m_usedTraitNames[i].c_str()
);
}
// First, make sure the used trait is flattened
tCls->importUsedTraits(ar);
findTraitMethodsToImport(ar, tCls);
// Import any interfaces implemented
tCls->getInterfaces(ar, m_bases, false);
importTraitRequirements(ar, tCls);
}
// Apply rules
@@ -782,7 +894,7 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
}
std::map<string, MethodStatementPtr> importedTraitMethods;
std::vector<std::pair<string,const TraitMethod*> > importedTraitsWithOrigName;
std::vector<std::pair<string,const TraitMethod*>> importedTraitsWithOrigName;
// Actually import the methods
for (MethodToTraitListMap::const_iterator
@@ -796,7 +908,11 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
}
// Consistency checking: each name must only refer to one imported method
if (iter->second.size() > 1) {
Compiler::Error(Compiler::MethodInMultipleTraits, getStmt());
getStmt()->analysisTimeFatal(
Compiler::MethodInMultipleTraits,
Strings::METHOD_IN_MULTIPLE_TRAITS,
iter->first.c_str()
);
} else {
TraitMethodList::const_iterator traitMethIter = iter->second.begin();
if ((traitMethIter->m_modifiers ? traitMethIter->m_modifiers :
@@ -807,13 +923,6 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
continue;
}
}
if (traitMethIter->m_modifiers &&
traitMethIter->m_modifiers->isStatic()) {
Compiler::Error(Compiler::InvalidAccessModifier,
traitMethIter->m_modifiers);
continue;
}
string sourceName = traitMethIter->m_ruleStmt ?
Util::toLower(((TraitAliasStatement*)traitMethIter->m_ruleStmt.get())->
getMethodName()) : iter->first;
@@ -1134,8 +1243,7 @@ void ClassScope::getInterfaces(AnalysisResultConstPtr ar,
if (cls && cls->isRedeclaring()) {
cls = self->findExactClass(cls);
}
if (cls) names.push_back(cls->getDocName());
else names.push_back(*it);
names.push_back(cls ? cls->getDocName() : *it);
if (cls && recursive) {
cls->getInterfaces(ar, names, true);
}
+34 -3
Ver Arquivo
@@ -24,8 +24,9 @@
#include "hphp/compiler/statement/trait_prec_statement.h"
#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/compiler/json.h"
#include "hphp/util/functional.h"
#include "hphp/util/hash-map-typedefs.h"
#include "hphp/compiler/option.h"
namespace HPHP {
@@ -173,6 +174,7 @@ public:
* Get/set attributes.
*/
void setSystem();
bool isSystem() const { return m_attribute & System; }
void setAttribute(Attribute attr) { m_attribute |= attr;}
void clearAttribute(Attribute attr) { m_attribute &= ~attr;}
bool getAttribute(Attribute attr) const {
@@ -301,17 +303,29 @@ public:
}
}
const boost::container::flat_set<std::string>& getTraitRequiredExtends()
const {
return m_traitRequiredExtends;
}
const boost::container::flat_set<std::string>& getTraitRequiredImplements()
const {
return m_traitRequiredImplements;
}
const std::vector<std::string> &getUsedTraitNames() const {
return m_usedTraitNames;
}
const std::vector<std::pair<std::string, std::string> > &getTraitAliases()
const std::vector<std::pair<std::string, std::string>>& getTraitAliases()
const {
return m_traitAliases;
}
void addTraitAlias(TraitAliasStatementPtr aliasStmt);
void addTraitRequirement(const std::string &requiredName, bool isExtends);
void importUsedTraits(AnalysisResultPtr ar);
/**
@@ -369,6 +383,16 @@ public:
bool canSkipCreateMethod(AnalysisResultConstPtr ar) const;
bool checkHasPropTable(AnalysisResultConstPtr ar);
const StringData* getFatalMessage() const {
return m_fatal_error_msg;
}
void setFatal(const AnalysisTimeFatalException& fatal) {
assert(m_fatal_error_msg == nullptr);
m_fatal_error_msg = makeStaticString(fatal.getMessage());
assert(m_fatal_error_msg != nullptr);
}
private:
// need to maintain declaration order for ClassInfo map
FunctionScopePtrVec m_functionsVec;
@@ -378,6 +402,8 @@ private:
UserAttributeMap m_userAttributes;
std::vector<std::string> m_usedTraitNames;
boost::container::flat_set<std::string> m_traitRequiredExtends;
boost::container::flat_set<std::string> m_traitRequiredImplements;
// m_traitAliases is used to support ReflectionClass::getTraitAliases
std::vector<std::pair<std::string, std::string> > m_traitAliases;
@@ -427,6 +453,9 @@ private:
// bases 32 through n are all known.
unsigned m_knownBases;
// holds the fact that accessing this class declaration is a fatal error
const StringData* m_fatal_error_msg = nullptr;
void addImportTraitMethod(const TraitMethod &traitMethod,
const std::string &methName);
void informClosuresAboutScopeClone(ConstructPtr root,
@@ -447,6 +476,8 @@ private:
void findTraitMethodsToImport(AnalysisResultPtr ar, ClassScopePtr trait);
void importTraitRequirements(AnalysisResultPtr ar, ClassScopePtr trait);
MethodStatementPtr findTraitMethod(AnalysisResultPtr ar,
ClassScopePtr trait,
const std::string &methodName,
+1 -1
Ver Arquivo
@@ -18,7 +18,7 @@
#define incl_HPHP_COMPILER_ERROR_H_
#include "hphp/compiler/analysis/type.h"
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+1
Ver Arquivo
@@ -245,6 +245,7 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
Statement::KindOf stype = s->getKindOf();
switch (stype) {
case Statement::KindOfUseTraitStatement:
case Statement::KindOfTraitRequireStatement:
case Statement::KindOfTraitPrecStatement:
case Statement::KindOfTraitAliasStatement:
not_reached();
+1 -1
Ver Arquivo
@@ -37,7 +37,6 @@ CODE_ERROR_ENTRY(InvalidAttribute)
CODE_ERROR_ENTRY(UnknownTrait)
CODE_ERROR_ENTRY(MethodInMultipleTraits)
CODE_ERROR_ENTRY(UnknownTraitMethod)
CODE_ERROR_ENTRY(InvalidAccessModifier)
CODE_ERROR_ENTRY(CyclicDependentTraits)
CODE_ERROR_ENTRY(InvalidTraitStatement)
CODE_ERROR_ENTRY(RedeclaredTrait)
@@ -45,3 +44,4 @@ CODE_ERROR_ENTRY(InvalidInstantiation)
CODE_ERROR_ENTRY(InvalidYield)
CODE_ERROR_ENTRY(InvalidAwait)
CODE_ERROR_ENTRY(BadDefaultValueType)
CODE_ERROR_ENTRY(InvalidMethodDefinition)
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+269 -63
Ver Arquivo
@@ -20,6 +20,7 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/use_trait_statement.h"
#include "hphp/compiler/statement/trait_require_statement.h"
#include "hphp/compiler/statement/trait_prec_statement.h"
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/compiler/statement/typedef_statement.h"
@@ -28,6 +29,9 @@
#include "hphp/runtime/vm/unit.h"
#include "hphp/util/hash.h"
#include <deque>
#include <utility>
namespace HPHP {
DECLARE_BOOST_TYPES(ClosureExpression);
@@ -95,6 +99,7 @@ public:
IterKind kind;
Id id;
};
#define O(name, imm, pop, push, flags) \
void name(imm);
#define NA
@@ -106,7 +111,7 @@ public:
typ1 a1, typ2 a2, typ3 a3
#define FOUR(typ1, typ2, typ3, typ4) \
typ1 a1, typ2 a2, typ3 a3, typ4 a4
#define MA std::vector<uchar>
#define MA std::vector<unsigned char>
#define BLA std::vector<Label*>&
#define SLA std::vector<StrOff>&
#define ILA std::vector<IterPair>&
@@ -118,7 +123,8 @@ public:
#define SA const StringData*
#define AA ArrayData*
#define BA Label&
#define OA unsigned char
#define OA(type) type
#define VSA std::vector<std::string>&
OPCODES
#undef O
#undef NA
@@ -139,6 +145,7 @@ public:
#undef AA
#undef BA
#undef OA
#undef VSA
private:
ConstructPtr m_node;
UnitEmitter& m_ue;
@@ -316,14 +323,137 @@ public:
class Funclet {
public:
Funclet(Thunklet* body, Label* entry) : m_body(body), m_entry(entry) {}
explicit Funclet(Thunklet* body)
: m_body(body) {
}
Thunklet* m_body;
Label* m_entry;
Label m_entry;
};
DECLARE_BOOST_TYPES(ControlTarget);
/*
* The structure represents a code path that potentially requires
* running finally blocks. A code path has an assigned state ID that
* is used inside switch statements emitted at the end of finally
* blocks. It also has an optional label (the destination to jump
* to after all the required finally blocks are run).
*/
struct ControlTarget {
static const int k_unsetState;
explicit ControlTarget(EmitterVisitor* router);
~ControlTarget();
// Manage state ID reuse.
bool isRegistered();
EmitterVisitor* m_visitor;
// The target to jump to once all the necessary finally blocks are run.
Label m_label;
// The state ID that identifies this control target inside finally
// epilogues. This ID assigned to the "state" unnamed local variable.
int m_state;
};
struct ControlTargetInfo {
ControlTargetInfo() : used(false) {}
ControlTargetInfo(ControlTargetPtr t, bool b) : target(t), used(b) {}
ControlTargetPtr target;
bool used;
};
DECLARE_BOOST_TYPES(Region);
/*
* Region represents a single level of the unified stack
* of constructs that are meaningful from the point of view of finally
* implementation. The levels are used to keep track of the information
* such as the control targets that can be taken inside a block.
*/
class Region {
public:
enum Kind {
// Top-level (global) context.
Global,
// Function body / method body entry.
FuncBody,
// Entry for finally fault funclets emitted after the body of
// a function
FaultFunclet,
// Region by a finally clause
TryFinally,
// Finally block entry (begins after catches ends after finally)
Finally,
// Loop or switch statement.
LoopOrSwitch,
};
typedef Emitter::IterPair IterPair;
typedef std::vector<IterPair> IterVec;
Region(Region::Kind kind, RegionPtr parent);
// Helper for establishing the maximal depth of break / continue
// control targets that are allocated.
int getBreakContinueDepth();
// Returns the maximal break / continue depth admissable (aka the
// number of nested loops).
int getMaxBreakContinueDepth();
int getMaxState();
// The number of cases to be emitted. This is a helper used in
// establishing whether one of the optimized cases can be used.
int getCaseCount();
bool isForeach() { return m_iterId != -1; }
bool isTryFinally() { return m_kind == Region::Kind::TryFinally; }
bool isFinally() { return m_kind == Region::Kind::Finally; }
bool isBreakUsed(int i) {
auto it = m_breakTargets.find(i);
if (it == m_breakTargets.end()) return false;
return it->second.used;
}
bool isContinueUsed(int i) {
auto it = m_continueTargets.find(i);
if (it == m_continueTargets.end()) return false;
return it->second.used;
}
Region::Kind m_kind;
// Only used for loop / break kind of entries.
Id m_iterId;
IterKind m_iterKind;
// Because of a bug in code emission, functions sometimes have
// inconsistent return flavors. Therefore instead of a single
// return control target, there need to be one return control
// target per flavor used. Once the bug is removed, this code
// can be simplified.
std::map<char, ControlTargetInfo> m_returnTargets;
// Break and continue control targets identified by their depth.
std::map<int, ControlTargetInfo> m_breakTargets;
std::map<int, ControlTargetInfo> m_continueTargets;
// Goto control targets. Each goto control target is identified
// by the name of the destination label.
std::map<StringData*, ControlTargetInfo, string_data_lt> m_gotoTargets;
// A set of goto labels occurrning inside the statement represented
// by this entry. This value is used for establishing whether
// a finally block needs to be executed when performing gotos.
std::set<StringData*, string_data_lt> m_gotoLabels;
// The label denoting the beginning of a finally block inside the
// current try. Only used when the entry kind is a try statement.
Label m_finallyLabel;
// The parent entry.
RegionPtr m_parent;
};
class EmitterVisitor {
friend class UnsetUnnamedLocalThunklet;
friend class FuncFinisher;
public:
typedef std::vector<int> IndexChain;
typedef Emitter::IterPair IterPair;
typedef std::vector<IterPair> IterVec;
explicit EmitterVisitor(UnitEmitter& ue);
~EmitterVisitor();
@@ -332,9 +462,10 @@ public:
void visitKids(ConstructPtr c);
void visit(FileScopePtr file);
void assignLocalVariableIds(FunctionScopePtr fs);
void assignFinallyVariableIds();
void fixReturnType(Emitter& e, FunctionCallPtr fn,
Func* builtinFunc = nullptr);
typedef std::vector<int> IndexChain;
void visitListAssignmentLHS(Emitter& e, ExpressionPtr exp,
IndexChain& indexChain,
std::vector<IndexChain*>& chainList);
@@ -349,7 +480,7 @@ public:
bool evalStackIsUnknown() { return m_evalStackIsUnknown; }
void popEvalStack(char symFlavor, int arg = -1, int pos = -1);
void popSymbolicLocal(Op opcode, int arg = -1, int pos = -1);
void popEvalStackLMany();
void popEvalStackMMany();
void popEvalStackMany(int len, char symFlavor);
void popEvalStackCVMany(int len);
void pushEvalStack(char symFlavor);
@@ -370,16 +501,27 @@ public:
|| isJumpTarget(m_ue.bcPos())
|| (instrFlags(getPrevOpcode()) & TF) == 0);
}
FuncEmitter* getFuncEmitter() { return m_curFunc; }
Id getStateLocal() {
assert(m_stateLocal >= 0);
return m_stateLocal;
}
Id getRetLocal() {
assert(m_retLocal >= 0);
return m_retLocal;
}
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) {
@@ -437,36 +579,11 @@ private:
FuncEmitter* m_fe;
};
class ControlTargets {
class CatchRegion {
public:
ControlTargets(Id itId, bool itRef, Label& brkTarg, Label& cntTarg)
: m_itId(itId), m_itRef(itRef), m_brkTarg(brkTarg), m_cntTarg(cntTarg)
{}
Id m_itId;
bool m_itRef;
Label& m_brkTarg; // Jump here for "break;" (after doing IterFree)
Label& m_cntTarg; // Jump here for "continue;"
};
class ControlTargetPusher {
public:
ControlTargetPusher(EmitterVisitor* e, Id itId, bool itRef, Label& brkTarg,
Label& cntTarg) : m_e(e) {
e->m_controlTargets.push_front(ControlTargets(itId, itRef, brkTarg,
cntTarg));
}
~ControlTargetPusher() {
m_e->m_controlTargets.pop_front();
}
private:
EmitterVisitor* m_e;
};
class ExnHandlerRegion {
public:
ExnHandlerRegion(Offset start, Offset end) : m_start(start),
CatchRegion(Offset start, Offset end) : m_start(start),
m_end(end) {}
~ExnHandlerRegion() {
~CatchRegion() {
for (std::vector<std::pair<StringData*, Label*> >::const_iterator it =
m_catchLabels.begin(); it != m_catchLabels.end(); it++) {
delete it->second;
@@ -480,18 +597,22 @@ private:
class FaultRegion {
public:
FaultRegion(Offset start, Offset end, Id iterId, IterKind kind)
FaultRegion(Offset start,
Offset end,
Label* func,
Id iterId,
IterKind kind)
: m_start(start)
, m_end(end)
, m_func(func)
, m_iterId(iterId)
, m_iterKind(kind)
{}
, m_iterKind(kind) {}
Offset m_start;
Offset m_end;
Label* m_func;
Id m_iterId;
IterKind m_iterKind;
Label m_func; // note: a pointer to this is handed out to the Funclet
};
class FPIRegion {
@@ -513,9 +634,6 @@ private:
int defI;
};
private:
void emitFatal(Emitter& e, const char* message);
private:
static const size_t kMinStringSwitchCases = 8;
UnitEmitter& m_ue;
@@ -542,23 +660,33 @@ private:
typedef tbb::concurrent_hash_map<const StringData*, int,
StringDataHashCompare> EmittedClosures;
static EmittedClosures s_emittedClosures;
std::deque<ControlTargets> m_controlTargets;
std::deque<Funclet> m_funclets;
std::deque<ExnHandlerRegion*> m_exnHandlers;
std::deque<Funclet*> m_funclets;
std::map<StatementPtr, Funclet*> m_memoizedFunclets;
std::deque<CatchRegion*> m_catchRegions;
std::deque<FaultRegion*> m_faultRegions;
std::deque<FPIRegion*> m_fpiRegions;
std::vector<Array> m_staticArrays;
std::set<std::string,stdltistr> m_hoistables;
LocationPtr m_tempLoc;
std::map<StringData*, Label, string_data_lt> m_gotoLabels;
std::vector<Label> m_yieldLabels;
// The stack of all Regions that this EmitterVisitor is currently inside
std::vector<RegionPtr> m_regions;
// The state IDs currently allocated for the "finally router" logic.
// See FIXME above the registerControlTarget() method.
std::set<int> m_states;
// Unnamed local variables used by the "finally router" logic
Id m_stateLocal;
Id m_retLocal;
MetaInfoBuilder m_metaInfo;
public:
bool checkIfStackEmpty(const char* forInstruction) const;
void unexpectedStackSym(char sym, const char* where) const;
int scanStackForLocation(int iLast);
void buildVectorImm(std::vector<uchar>& vectorImm,
void buildVectorImm(std::vector<unsigned char>& vectorImm,
int iFirst, int iLast, bool allowW,
Emitter& e);
enum class PassByRefKind {
@@ -570,26 +698,20 @@ public:
void emitAGet(Emitter& e);
void emitCGetL2(Emitter& e);
void emitCGetL3(Emitter& e);
void emitPushL(Emitter& e);
void emitCGet(Emitter& e);
void emitVGet(Emitter& e);
void emitIsset(Emitter& e);
void emitIsNull(Emitter& e);
void emitIsArray(Emitter& e);
void emitIsObject(Emitter& e);
void emitIsString(Emitter& e);
void emitIsInt(Emitter& e);
void emitIsDouble(Emitter& e);
void emitIsBool(Emitter& e);
void emitIsType(Emitter& e, IsTypeOp op);
void emitEmpty(Emitter& e);
void emitUnset(Emitter& e, ExpressionPtr exp = ExpressionPtr());
void emitVisitAndUnset(Emitter& e, ExpressionPtr exp);
void emitSet(Emitter& e);
void emitSetOp(Emitter& e, int op);
void emitBind(Emitter& e);
void emitIncDec(Emitter& e, unsigned char cop);
void emitIncDec(Emitter& e, IncDecOp cop);
void emitPop(Emitter& e);
void emitConvertToCell(Emitter& e);
void emitFreePendingIters(Emitter& e);
void emitConvertToCellIfVar(Emitter& e);
void emitConvertToCellOrLoc(Emitter& e);
void emitConvertSecondToCell(Emitter& e);
@@ -610,7 +732,6 @@ public:
void emitStringSwitch(Emitter& e, SwitchStatementPtr s,
std::vector<Label>& caseLabels, Label& done,
const SwitchState& state);
void emitIterBreak(Emitter& e, uint64_t n, Label& targ);
void markElem(Emitter& e);
void markNewElem(Emitter& e);
@@ -676,31 +797,90 @@ public:
bool emitCallUserFunc(Emitter& e, SimpleFunctionCallPtr node);
Func* canEmitBuiltinCall(const std::string& name, int numParams);
void emitFuncCall(Emitter& e, FunctionCallPtr node);
void emitFuncCall(Emitter& e, FunctionCallPtr node,
const char* nameOverride = nullptr,
ExpressionListPtr paramsOverride = nullptr);
void emitFuncCallArg(Emitter& e, ExpressionPtr exp, int paramId);
void emitBuiltinCallArg(Emitter& e, ExpressionPtr exp, int paramId,
bool byRef);
void emitBuiltinDefaultArg(Emitter& e, Variant& v, DataType t, int paramId);
void emitClass(Emitter& e, ClassScopePtr cNode, bool topLevel);
void emitTypedef(Emitter& e, TypedefStatementPtr);
void emitForeachListAssignment(Emitter& e, ListAssignmentPtr la,
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,
FatalOp k = FatalOp::Runtime);
void addFunclet(Thunklet* body, Label* entry);
// Emits a Jmp or IterBreak instruction to the specified target, freeing
// the specified iterator variables. emitJump() cannot be used to leave a
// try region, except if it jumps to the m_finallyLabel of the try region.
void emitJump(Emitter& e, IterVec& iters, Label& target);
// These methods handle the return, break, continue, and goto operations.
// These methods are aware of try/finally blocks and foreach blocks and
// will free iterators and jump to finally epilogues as appropriate.
void emitReturn(Emitter& e, char sym, StatementPtr s);
void emitBreak(Emitter& e, int depth, StatementPtr s);
void emitContinue(Emitter& e, int depth, StatementPtr s);
void emitGoto(Emitter& e, StringData* name, StatementPtr s);
// Helper methods for emitting IterFree instructions
void emitIterFree(Emitter& e, IterVec& iters);
void emitIterFreeForReturn(Emitter& e);
// A "finally epilogue" is a blob of bytecode that comes after an inline
// copy of a "finally" clause body. Finally epilogues are used to ensure
// that that the bodies of finally clauses are executed whenever a return,
// break, continue, or goto operation jumps out of their corresponding
// "try" blocks.
void emitFinallyEpilogue(Emitter& e, Region* entry);
void emitReturnTrampoline(Emitter& e, Region* entry,
std::vector<Label*>& cases, char sym);
void emitBreakTrampoline(Emitter& e, Region* entry,
std::vector<Label*>& cases, int depth);
void emitContinueTrampoline(Emitter& e, Region* entry,
std::vector<Label*>& cases, int depth);
void emitGotoTrampoline(Emitter& e, Region* entry,
std::vector<Label*>& cases, StringData* name);
Funclet* addFunclet(Thunklet* body);
Funclet* addFunclet(StatementPtr stmt,
Thunklet* body);
Funclet* getFunclet(StatementPtr stmt);
void emitFunclets(Emitter& e);
struct FaultIterInfo {
Id iterId;
IterKind kind;
};
void newFaultRegion(Offset start, Offset end, Thunklet* t,
void newFaultRegion(Offset start,
Offset end,
Label* entry,
FaultIterInfo = FaultIterInfo { -1, KindOfIter });
void newFaultRegion(StatementPtr stmt,
Offset start,
Offset end,
Label* entry,
FaultIterInfo = FaultIterInfo { -1, KindOfIter });
void
newFaultRegionAndFunclet(Offset start,
Offset end,
Thunklet* t,
FaultIterInfo = FaultIterInfo { -1, KindOfIter });
void
newFaultRegionAndFunclet(StatementPtr stmt,
Offset start,
Offset end,
Thunklet* t,
FaultIterInfo = FaultIterInfo { -1, KindOfIter });
void newFPIRegion(Offset start, Offset end, Offset fpOff);
void copyOverExnHandlers(FuncEmitter* fe);
void copyOverCatchAndFaultRegions(FuncEmitter* fe);
void copyOverFPIRegions(FuncEmitter* fe);
void saveMaxStackCells(FuncEmitter* fe);
void finishFunc(Emitter& e, FuncEmitter* fe);
@@ -712,11 +892,37 @@ public:
void emitClassTraitAliasRule(PreClassEmitter* pce,
TraitAliasStatementPtr rule);
void emitClassUseTrait(PreClassEmitter* pce, UseTraitStatementPtr useStmt);
// Helper function for creating entries.
RegionPtr createRegion(StatementPtr s, Region::Kind kind);
// Enter/leave the passed in entry. Note that entries sometimes need be
// to be constructed before they are entered, or need to be accessed
// after they are left. This especially applies to constructs such
// as loops and try blocks.
void enterRegion(RegionPtr);
void leaveRegion(RegionPtr);
// Functions used for handling state IDs allocation.
// FIXME (#3275259): This should be moved into global / func
// body / fault funclet entries in order to optimize state
// allocation. See the task description for more details.
void registerControlTarget(ControlTarget* t);
void unregisterControlTarget(ControlTarget* t);
void registerReturn(StatementPtr s, Region* entry, char sym);
void registerYieldAwait(ExpressionPtr e);
ControlTargetPtr registerBreak(StatementPtr s, Region* entry, int depth,
bool alloc);
ControlTargetPtr registerContinue(StatementPtr s, Region* entry, int depth,
bool alloc);
ControlTargetPtr registerGoto(StatementPtr s, Region* entry,
StringData* name, bool alloc);
};
void emitAllHHBC(AnalysisResultPtr ar);
extern "C" {
String hphp_compiler_serialize_code_model_for(String code, String prefix);
Unit* hphp_compiler_parse(const char* code, int codeLen, const MD5& md5,
const char* filename);
Unit* hphp_build_native_func_unit(const HhbcExtFuncInfo* builtinFuncs,
+121 -96
Ver Arquivo
@@ -13,9 +13,13 @@
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/file_scope.h"
#include <sys/stat.h>
#include "folly/ScopeGuard.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/lambda_names.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/statement/statement_list.h"
@@ -23,11 +27,10 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/function_scope.h"
#include <sys/stat.h>
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.h"
#include "hphp/util/base.h"
#include "hphp/util/deprecated/base.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/statement/function_statement.h"
#include "hphp/compiler/analysis/variable_table.h"
@@ -36,15 +39,14 @@
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
FileScope::FileScope(const string &fileName, int fileSize, const MD5 &md5)
: BlockScope("", "", StatementPtr(), BlockScope::FileScope),
m_size(fileSize), m_md5(md5), m_module(false), m_privateInclude(false),
m_externInclude(false),
m_includeState(0), m_fileName(fileName), m_redeclaredFunctions(0) {
m_size(fileSize), m_md5(md5), m_includeState(0), m_system(false),
m_fileName(fileName), m_redeclaredFunctions(0) {
pushAttribute(); // for global scope
}
@@ -66,6 +68,11 @@ void FileScope::setFileLevel(StatementListPtr stmtList) {
}
}
void FileScope::setSystem() {
m_fileName = "/:" + m_fileName;
m_system = true;
}
FunctionScopePtr FileScope::setTree(AnalysisResultConstPtr ar,
StatementListPtr tree) {
m_tree = tree;
@@ -73,8 +80,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 +96,17 @@ 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();
LabelScopePtr labelScope(new LabelScope());
loc->file = file.getName().c_str();
loc->first(line, 0);
loc->last(line, 0);
BlockScopePtr scope;
@@ -100,16 +115,30 @@ void FileScope::cleanupForError(AnalysisResultConstPtr ar,
SimpleFunctionCallPtr e(
new SimpleFunctionCall(scope, loc, "throw_fatal", false, args,
ExpressionPtr()));
e->setThrowFatal();
ExpStatementPtr exp(new ExpStatement(scope, loc, e));
StatementListPtr stmts(new StatementList(scope, loc));
meth(e);
ExpStatementPtr exp(new ExpStatement(scope, labelScope, loc, e));
StatementListPtr stmts(new StatementList(scope, labelScope, 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,
@@ -233,9 +262,10 @@ void FileScope::addConstantDependency(AnalysisResultPtr ar,
}
void FileScope::analyzeProgram(AnalysisResultPtr ar) {
if (m_pseudoMain) {
m_pseudoMain->getStmt()->analyzeProgram(ar);
}
if (!m_pseudoMain) return;
m_pseudoMain->getStmt()->analyzeProgram(ar);
resolve_lambda_names(ar, shared_from_this());
}
ClassScopeRawPtr FileScope::resolveClass(ClassScopeRawPtr cls) {
@@ -300,80 +330,80 @@ bool FileScope::insertClassUtil(AnalysisResultPtr ar,
void FileScope::analyzeIncludesHelper(AnalysisResultPtr ar) {
m_includeState = 1;
if (m_pseudoMain) {
StatementList &stmts = *getStmt();
bool hoistOnly = false;
for (int i = 0, n = stmts.getCount(); i < n; i++) {
StatementPtr s = stmts[i];
if (!s) continue;
if (s->is(Statement::KindOfClassStatement) ||
s->is(Statement::KindOfInterfaceStatement)) {
SCOPE_EXIT { m_includeState = 2; };
ClassScopeRawPtr cls(
static_pointer_cast<InterfaceStatement>(s)->getClassScope());
if (hoistOnly) {
const string &parent = cls->getOriginalParent();
if (cls->getBases().size() > (parent.empty() ? 0 : 1)) {
continue;
}
if (!parent.empty()) {
ClassScopeRawPtr c = ar->findClass(parent);
if (!c || (c->isVolatile() &&
!resolveClass(c) && !checkClass(parent))) {
continue;
}
}
if (!m_pseudoMain) return;
StatementList &stmts = *getStmt();
bool hoistOnly = false;
for (int i = 0, n = stmts.getCount(); i < n; i++) {
StatementPtr s = stmts[i];
if (!s) continue;
if (s->is(Statement::KindOfClassStatement) ||
s->is(Statement::KindOfInterfaceStatement)) {
ClassScopeRawPtr cls(
static_pointer_cast<InterfaceStatement>(s)->getClassScope());
if (hoistOnly) {
const string &parent = cls->getOriginalParent();
if (cls->getBases().size() > (parent.empty() ? 0 : 1)) {
continue;
}
if (cls->isVolatile()) {
insertClassUtil(ar, cls, true);
}
continue;
}
if (s->is(Statement::KindOfFunctionStatement)) {
FunctionScopeRawPtr func(
static_pointer_cast<FunctionStatement>(s)->getFunctionScope());
if (func->isVolatile()) m_providedDefs.insert(func);
continue;
}
if (!hoistOnly && s->is(Statement::KindOfExpStatement)) {
ExpressionRawPtr exp(
static_pointer_cast<ExpStatement>(s)->getExpression());
if (exp && exp->is(Expression::KindOfIncludeExpression)) {
FileScopeRawPtr fs(
static_pointer_cast<IncludeExpression>(exp)->getIncludedFile(ar));
if (fs && fs->m_includeState != 1) {
if (!fs->m_includeState) {
if (m_module && fs->m_privateInclude) {
BOOST_FOREACH(BlockScopeRawPtr bs, m_providedDefs) {
fs->m_providedDefs.insert(bs);
}
}
fs->analyzeIncludesHelper(ar);
}
BOOST_FOREACH(BlockScopeRawPtr bs, fs->m_providedDefs) {
m_providedDefs.insert(bs);
}
if (!parent.empty()) {
ClassScopeRawPtr c = ar->findClass(parent);
if (!c || (c->isVolatile() &&
!resolveClass(c) && !checkClass(parent))) {
continue;
}
}
}
hoistOnly = true;
if (cls->isVolatile()) {
insertClassUtil(ar, cls, true);
}
continue;
}
if (s->is(Statement::KindOfFunctionStatement)) {
FunctionScopeRawPtr func(
static_pointer_cast<FunctionStatement>(s)->getFunctionScope());
if (func->isVolatile()) m_providedDefs.insert(func);
continue;
}
if (!hoistOnly && s->is(Statement::KindOfExpStatement)) {
ExpressionRawPtr exp(
static_pointer_cast<ExpStatement>(s)->getExpression());
if (exp && exp->is(Expression::KindOfIncludeExpression)) {
FileScopeRawPtr fs(
static_pointer_cast<IncludeExpression>(exp)->getIncludedFile(ar));
if (fs && fs->m_includeState != 1) {
if (!fs->m_includeState) {
fs->analyzeIncludesHelper(ar);
}
BOOST_FOREACH(BlockScopeRawPtr bs, fs->m_providedDefs) {
m_providedDefs.insert(bs);
}
continue;
}
}
}
hoistOnly = true;
}
m_includeState = 2;
}
void FileScope::analyzeIncludes(AnalysisResultPtr ar) {
if (!m_privateInclude && !m_includeState) {
if (!m_includeState) {
analyzeIncludesHelper(ar);
}
}
void FileScope::visit(AnalysisResultPtr ar,
void (*cb)(AnalysisResultPtr, StatementPtr, void*),
void *data)
{
void *data) {
if (m_pseudoMain) {
cb(ar, m_pseudoMain->getStmt(), data);
}
@@ -388,8 +418,11 @@ const string &FileScope::pseudoMainName() {
FunctionScopePtr FileScope::createPseudoMain(AnalysisResultConstPtr ar) {
StatementListPtr st = m_tree;
LabelScopePtr labelScope(new LabelScope());
FunctionStatementPtr f
(new FunctionStatement(BlockScopePtr(), LocationPtr(),
(new FunctionStatement(BlockScopePtr(),
labelScope,
LocationPtr(),
ModifierExpressionPtr(),
false, pseudoMainName(),
ExpressionListPtr(), TypeAnnotationPtr(),
@@ -425,24 +458,18 @@ string FileScope::outputFilebase() const {
static void getFuncScopesSet(BlockScopeRawPtrQueue &v,
const StringToFunctionScopePtrMap &funcMap) {
for (StringToFunctionScopePtrMap::const_iterator
iter = funcMap.begin(), end = funcMap.end();
iter != end; ++iter) {
FunctionScopePtr f = iter->second;
if (f->isUserFunction()) {
for (const auto& iter : funcMap) {
FunctionScopePtr f = iter.second;
if (f->getStmt()) {
v.push_back(f);
}
}
}
void FileScope::getScopesSet(BlockScopeRawPtrQueue &v) {
const StringToClassScopePtrVecMap &classes = getClasses();
for (StringToClassScopePtrVecMap::const_iterator iter = classes.begin(),
end = classes.end(); iter != end; ++iter) {
for (ClassScopePtrVec::const_iterator it = iter->second.begin(),
e = iter->second.end(); it != e; ++it) {
ClassScopePtr cls = *it;
if (cls->isUserClass()) {
for (const auto& clsVec : getClasses()) {
for (const auto cls : clsVec.second) {
if (cls->getStmt()) {
v.push_back(cls);
getFuncScopesSet(v, cls->getFunctions());
}
@@ -450,20 +477,17 @@ void FileScope::getScopesSet(BlockScopeRawPtrQueue &v) {
}
getFuncScopesSet(v, getFunctions());
if (const StringToFunctionScopePtrVecMap *redec = m_redeclaredFunctions) {
for (StringToFunctionScopePtrVecMap::const_iterator iter = redec->begin(),
end = redec->end(); iter != end; ++iter) {
FunctionScopePtrVec::const_iterator i = iter->second.begin(),
e = iter->second.end();
if (const auto redec = m_redeclaredFunctions) {
for (const auto& funcVec : *redec) {
auto i = funcVec.second.begin(), e = funcVec.second.end();
v.insert(v.end(), ++i, e);
}
}
}
void FileScope::getClassesFlattened(ClassScopePtrVec &classes) const {
for (StringToClassScopePtrVecMap::const_iterator it = m_classes.begin();
it != m_classes.end(); ++it) {
BOOST_FOREACH(ClassScopePtr cls, it->second) {
for (const auto& clsVec : m_classes) {
for (auto cls : clsVec.second) {
classes.push_back(cls);
}
}
@@ -486,3 +510,4 @@ void FileScope::serialize(JSON::DocTarget::OutputStream &out) const {
ms.done();
}
}
+20 -13
Ver Arquivo
@@ -17,14 +17,16 @@
#ifndef incl_HPHP_FILE_SCOPE_H_
#define incl_HPHP_FILE_SCOPE_H_
#include <string>
#include <map>
#include <boost/algorithm/string.hpp>
#include "hphp/compiler/analysis/block_scope.h"
#include "hphp/compiler/analysis/function_container.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/code_generator.h"
#include <boost/graph/adjacency_list.hpp>
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
#include "hphp/util/md5.h"
namespace HPHP {
@@ -62,6 +64,7 @@ public:
IsFoldable = 0x1000,// function can be constant folded
NeedsActRec = 0x2000,// builtin function needs ActRec
AllowOverride = 0x4000,// allow override of systemlib or builtin
NeedsFinallyLocals = 0x8000,
};
typedef boost::adjacency_list<boost::setS, boost::vecS> Graph;
@@ -77,6 +80,7 @@ public:
const std::string &getName() const { return m_fileName;}
const MD5& getMd5() const { return m_md5; }
void setMd5(const MD5& md5) { m_md5 = md5; }
StatementListPtr getStmt() const { return m_tree;}
const StringToClassScopePtrVecMap &getClasses() const {
return m_classes;
@@ -107,8 +111,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,8 +145,12 @@ public:
const std::string &decname);
void addClassAlias(const std::string& target, const std::string& alias) {
m_classAliasMap.insert(std::make_pair(Util::toLower(target),
Util::toLower(alias)));
m_classAliasMap.insert(
std::make_pair(
boost::to_lower_copy(target),
boost::to_lower_copy(alias)
)
);
}
std::multimap<std::string,std::string> const& getClassAliases() const {
@@ -147,7 +158,7 @@ public:
}
void addTypeAliasName(const std::string& name) {
m_typeAliasNames.insert(Util::toLower(name));
m_typeAliasNames.insert(boost::to_lower_copy(name));
}
std::set<std::string> const& getTypeAliasNames() const {
@@ -162,10 +173,8 @@ public:
m_vertex = vertex;
}
void setModule() { m_module = true; }
void setPrivateInclude() { m_privateInclude = true; }
bool isPrivateInclude() const { return m_privateInclude && !m_externInclude; }
void setExternInclude() { m_externInclude = true; }
void setSystem();
bool isSystem() const { return m_system; }
void analyzeProgram(AnalysisResultPtr ar);
void analyzeIncludes(AnalysisResultPtr ar);
@@ -195,10 +204,8 @@ public:
private:
int m_size;
MD5 m_md5;
unsigned m_module : 1;
unsigned m_privateInclude : 1;
unsigned m_externInclude : 1;
unsigned m_includeState : 2;
unsigned m_system : 1;
std::vector<int> m_attributes;
std::string m_fileName;
+1 -1
Ver Arquivo
@@ -24,7 +24,7 @@ namespace HPHP {
class CodeGenerator;
DECLARE_BOOST_TYPES(AnalysisResult);
DECLARE_BOOST_TYPES(FunctionScope);
DECLARE_EXTENDED_BOOST_TYPES(FunctionScope);
DECLARE_BOOST_TYPES(ClassScope);
DECLARE_BOOST_TYPES(FunctionContainer);
+15 -6
Ver Arquivo
@@ -292,7 +292,8 @@ bool FunctionScope::hasUserAttr(const char *attr) const {
}
bool FunctionScope::isZendParamMode() const {
return m_attributeClassInfo & ClassInfo::ZendParamMode;
return m_attributeClassInfo &
(ClassInfo::ZendParamModeNull | ClassInfo::ZendParamModeFalse);
}
bool FunctionScope::isPublic() const {
@@ -354,6 +355,11 @@ bool FunctionScope::needsActRec() const {
return res;
}
bool FunctionScope::needsFinallyLocals() const {
bool res = (m_attribute & FileScope::NeedsFinallyLocals);
return res;
}
bool FunctionScope::mayContainThis() {
return inPseudoMain() || getContainingClass() ||
(isClosure() && !m_modifiers->isStatic());
@@ -842,11 +848,14 @@ bool FunctionScope::popReturnType() {
m_prevReturn.reset();
return false;
}
if (!isFirstPass()) {
Logger::Verbose("Corrected function return type %s -> %s",
m_prevReturn->toString().c_str(),
m_returnType->toString().c_str());
}
Logger::Verbose("Corrected %s's return type %s -> %s",
getFullName().c_str(),
m_prevReturn->toString().c_str(),
m_returnType->toString().c_str());
} else {
Logger::Verbose("Set %s's return type %s",
getFullName().c_str(),
m_returnType->toString().c_str());
}
} else if (!m_prevReturn) {
return false;
+6 -2
Ver Arquivo
@@ -20,8 +20,9 @@
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/compiler/analysis/block_scope.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/json.h"
#include "hphp/util/json.h"
#include "hphp/util/hash-map-typedefs.h"
#include "hphp/parser/parser.h"
namespace HPHP {
@@ -95,6 +96,7 @@ public:
* What kind of function this is.
*/
bool isUserFunction() const { return !m_system && !isNative(); }
bool isSystem() const { return m_system; }
bool isDynamic() const { return m_dynamic; }
bool isPublic() const;
bool isProtected() const;
@@ -226,6 +228,8 @@ public:
bool allowOverride() const;
void setAllowOverride();
bool needsFinallyLocals() const;
/**
* Whether this function is a runtime helper function
*/
@@ -385,7 +389,7 @@ public:
ReadWriteMutex &getInlineMutex() { return m_inlineMutex; }
DECLARE_BOOST_TYPES(FunctionInfo);
DECLARE_EXTENDED_BOOST_TYPES(FunctionInfo);
static void RecordFunctionInfo(std::string fname, FunctionScopePtr func);
+59
Ver Arquivo
@@ -0,0 +1,59 @@
/*
+----------------------------------------------------------------------+
| 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_LABEL_SCOPE_H_
#define incl_HPHP_LABEL_SCOPE_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/deprecated/base.h"
#include <vector>
#include <string>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
class Statement;
DECLARE_BOOST_TYPES(Statement);
class LabelScope {
public:
class LabelInfo {
public:
LabelInfo(StatementPtr s, const std::string& name)
: m_stmt(s), m_name(name) {}
StatementPtr getStatement() const { return m_stmt; }
const std::string& getName() const { return m_name; }
private:
StatementPtr m_stmt;
std::string m_name;
};
const std::vector<LabelInfo>& getLabels() const { return m_labels; }
void addLabel(StatementPtr s, const std::string& label) {
m_labels.push_back(LabelInfo(s, label));
}
private:
std::vector<LabelInfo> m_labels;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_LABEL_SCOPE_H_
+156
Ver Arquivo
@@ -0,0 +1,156 @@
/*
+----------------------------------------------------------------------+
| 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/analysis/lambda_names.h"
#include <set>
#include "folly/ScopeGuard.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/function_statement.h"
#include "hphp/compiler/expression/closure_expression.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
namespace {
struct NameScope {
NameScope* const prev;
VariableTablePtr const vars;
};
struct Walker {
explicit Walker(AnalysisResultPtr ar)
: m_curScope{nullptr}
, m_ar{ar}
{}
void walk_functions(const FunctionContainer& funcCont) {
for (auto& kv : funcCont.getFunctions()) {
walk_function(kv.second);
}
}
private:
void visit_closure(ClosureExpressionPtr ce) {
auto const cfunc = ce->getClosureFunction();
with_scope(
cfunc->getScope()->getVariables(),
[&] {
walk_ast(cfunc->getStmts());
}
);
if (ce->type() != ClosureType::Short) return;
if (ce->captureState() == ClosureExpression::CaptureState::Known) {
return;
}
auto const paramNames = ce->collectParamNames();
std::set<std::string> mentioned;
cfunc->getScope()->getVariables()->getNames(mentioned);
std::set<std::string> toCapture;
for (auto& m : mentioned) {
if (paramNames.count(m)) continue;
if (m == "this") {
toCapture.insert("this");
continue;
}
for (auto scope = m_curScope; scope; scope = scope->prev) {
if (scope->vars->getSymbol(m)) {
toCapture.insert(m);
break;
}
}
}
if (cfunc->getFunctionScope()->containsThis()) {
toCapture.insert("this");
}
ce->setCaptureList(m_ar, toCapture);
}
void walk_ast(ConstructPtr node) {
if (!node) return;
if (dynamic_pointer_cast<MethodStatement>(node)) {
// Don't descend into nested non-closure functions, or functions
// in the psuedo-main.
return;
}
if (auto ce = dynamic_pointer_cast<ClosureExpression>(node)) {
visit_closure(ce);
return;
}
for (int i = 0; i < node->getKidCount(); ++i) {
walk_ast(node->getNthKid(i));
}
}
void walk_function(const FunctionScopePtr& fscope) {
if (fscope->isClosure()) return;
auto ms = dynamic_pointer_cast<MethodStatement>(fscope->getStmt());
ConstructPtr node(ms->getStmts());
with_scope(
fscope->getVariables(),
[&] {
walk_ast(node);
}
);
}
template<class Func>
void with_scope(const VariableTablePtr& scopeVars, Func func) {
auto newScope = NameScope { m_curScope, scopeVars };
m_curScope = &newScope;
SCOPE_EXIT { m_curScope = m_curScope->prev; };
func();
}
private:
NameScope* m_curScope;
AnalysisResultPtr m_ar;
};
}
//////////////////////////////////////////////////////////////////////
void resolve_lambda_names(AnalysisResultPtr ar, const FileScopePtr& fscope) {
Walker walker(ar);
ClassScopePtrVec classScopes;
fscope->getClassesFlattened(classScopes);
for (auto& cls : classScopes) {
walker.walk_functions(*cls);
}
walker.walk_functions(*fscope);
}
//////////////////////////////////////////////////////////////////////
}
+39
Ver Arquivo
@@ -0,0 +1,39 @@
/*
+----------------------------------------------------------------------+
| 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_ANALYSIS_LAMBDA_NAMES_H_
#define incl_HPHP_COMPILER_ANALYSIS_LAMBDA_NAMES_H_
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
/*
* After the first analysis pass over a file, this pass must run to
* resolve names for lambda expressions and determine their automatic
* capture lists.
*/
void resolve_lambda_names(AnalysisResultPtr ar, const FileScopePtr&);
//////////////////////////////////////////////////////////////////////
}
#endif
+2 -1
Ver Arquivo
@@ -623,7 +623,8 @@ public:
e->setLocation(sub->getLocation());
e->setBlockScope(sub->getScope());
ExpStatementPtr exp(
new ExpStatement(sub->getScope(), sub->getLocation(), e));
new ExpStatement(sub->getScope(), sub->getLabelScope(),
sub->getLocation(), e));
sl->insertElement(exp, ix);
}
}
+5 -5
Ver Arquivo
@@ -24,7 +24,7 @@ namespace HPHP { namespace Compiler {
static void collapseJmp(Offset* offsetPtr, Op* instr, Op* start) {
if (offsetPtr) {
Op* dest = instr + *offsetPtr;
while (*dest == OpJmp && dest != instr) {
while (isUnconditionalJmp(*dest) && dest != instr) {
dest = start + instrJumpTarget(start, dest - start);
}
*offsetPtr = dest - instr;
@@ -91,10 +91,10 @@ Peephole::Peephole(UnitEmitter &ue, MetaInfoBuilder& metaInfo)
// fallthrough
incDecOp:
if (imm->u_OA == PostInc) {
imm->u_OA = PreInc;
} else if (imm->u_OA == PostDec) {
imm->u_OA = PreDec;
if (static_cast<IncDecOp>(imm->u_OA) == IncDecOp::PostInc) {
imm->u_OA = static_cast<unsigned char>(IncDecOp::PreInc);
} else if (static_cast<IncDecOp>(imm->u_OA) == IncDecOp::PostDec) {
imm->u_OA = static_cast<unsigned char>(IncDecOp::PreDec);
}
break;
default:
+3 -2
Ver Arquivo
@@ -18,9 +18,10 @@
#define incl_HPHP_SYMBOL_TABLE_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
#include "hphp/util/util.h"
#include "hphp/util/lock.h"
#include "hphp/util/hash-map-typedefs.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -29,7 +30,7 @@ class BlockScope;
class CodeGenerator;
class Variant;
DECLARE_BOOST_TYPES(Construct);
DECLARE_BOOST_TYPES(Type);
DECLARE_EXTENDED_BOOST_TYPES(Type);
DECLARE_BOOST_TYPES(AnalysisResult);
DECLARE_BOOST_TYPES(SymbolTable);
DECLARE_BOOST_TYPES(FunctionScope);
+3
Ver Arquivo
@@ -21,6 +21,7 @@
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/vm/runtime.h"
#include <boost/format.hpp>
using namespace HPHP;
@@ -70,6 +71,8 @@ void Type::InitTypeHintMap() {
s_HHTypeHintTypes["double"] = Type::Double;
s_HHTypeHintTypes["float"] = Type::Double;
s_HHTypeHintTypes["string"] = Type::String;
// Type::Numeric doesn't include numeric strings; this is intentional
s_HHTypeHintTypes["num"] = Type::Numeric;
s_HHTypeHintTypes["resource"] = Type::Resource;
s_HHTypeHintTypes["callable"] = Type::Variant;
}
+2 -2
Ver Arquivo
@@ -18,8 +18,8 @@
#define incl_HPHP_TYPE_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/json.h"
#include "hphp/util/case-insensitive.h"
#include "hphp/compiler/json.h"
#include "hphp/util/functional.h"
#include "hphp/runtime/base/types.h"
+3 -1
Ver Arquivo
@@ -428,7 +428,9 @@ TypePtr VariableTable::add(Symbol *sym, TypePtr type,
type = setType(ar, sym, type, true);
if (sym->isParameter()) {
auto p = dynamic_pointer_cast<ParameterExpression>(construct);
if (p) sym->setDeclaration(construct);
if (p) {
sym->setDeclaration(construct);
}
} else {
sym->setDeclaration(construct);
}
+2 -1
Ver Arquivo
@@ -20,6 +20,7 @@
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/util/hash-map-typedefs.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -296,7 +297,7 @@ public:
* GlobalVariables class to make ThreadLocal<GlobalVaribles> work.
* This data structure is only needed by global scope.
*/
DECLARE_BOOST_TYPES(StaticGlobalInfo);
DECLARE_EXTENDED_BOOST_TYPES(StaticGlobalInfo);
struct StaticGlobalInfo {
Symbol *sym;
VariableTable *variables; // where this variable was from
+38 -124
Ver Arquivo
@@ -50,8 +50,7 @@ using namespace HPHP;
bool BuiltinSymbols::Loaded = false;
StringBag BuiltinSymbols::s_strings;
StringToFunctionScopePtrMap BuiltinSymbols::s_functions;
AnalysisResultPtr BuiltinSymbols::s_systemAr;
const char *const BuiltinSymbols::GlobalNames[] = {
"HTTP_RAW_POST_DATA",
@@ -86,12 +85,7 @@ const char *BuiltinSymbols::SystemClasses[] = {
nullptr
};
StringToClassScopePtrMap BuiltinSymbols::s_classes;
VariableTablePtr BuiltinSymbols::s_variables;
ConstantTablePtr BuiltinSymbols::s_constants;
StringToTypePtrMap BuiltinSymbols::s_superGlobals;
AnalysisResultPtr BuiltinSymbols::s_systemAr;
void *BuiltinSymbols::s_handle_main = nullptr;
///////////////////////////////////////////////////////////////////////////////
@@ -218,7 +212,6 @@ FunctionScopePtr BuiltinSymbols::ImportFunctionScopePtr(AnalysisResultPtr ar,
}
void BuiltinSymbols::ImportExtFunctions(AnalysisResultPtr ar,
StringToFunctionScopePtrMap &map,
ClassInfo *cls) {
const ClassInfo::MethodVec &methods = cls->getMethodsVec();
for (auto it = methods.begin(); it != methods.end(); ++it) {
@@ -228,14 +221,13 @@ void BuiltinSymbols::ImportExtFunctions(AnalysisResultPtr ar,
}
FunctionScopePtr f = ImportFunctionScopePtr(ar, cls, *it);
assert(!map[f->getName()]);
map[f->getName()] = f;
ar->addSystemFunction(f);
}
}
void BuiltinSymbols::ImportExtFunctions(AnalysisResultPtr ar,
FunctionScopePtrVec &vec,
ClassInfo *cls) {
void BuiltinSymbols::ImportExtMethods(AnalysisResultPtr ar,
FunctionScopePtrVec &vec,
ClassInfo *cls) {
const ClassInfo::MethodVec &methods = cls->getMethodsVec();
for (auto it = methods.begin(); it != methods.end(); ++it) {
FunctionScopePtr f = ImportFunctionScopePtr(ar, cls, *it);
@@ -287,7 +279,7 @@ void BuiltinSymbols::ImportExtConstants(AnalysisResultPtr ar,
ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
ClassInfo *cls) {
FunctionScopePtrVec methods;
ImportExtFunctions(ar, methods, cls);
ImportExtMethods(ar, methods, cls);
ClassInfo::InterfaceVec ifaces = cls->getInterfacesVec();
String parent = cls->getParentClass();
@@ -325,8 +317,7 @@ void BuiltinSymbols::ImportExtClasses(AnalysisResultPtr ar) {
}
ClassScopePtr cl = ImportClassScopePtr(ar, it->second);
assert(!s_classes[cl->getName()]);
s_classes[cl->getName()] = cl;
ar->addSystemClass(cl);
}
}
@@ -338,13 +329,11 @@ bool BuiltinSymbols::Load(AnalysisResultPtr ar) {
ClassInfo::Load();
// load extension functions first, so system/php may call them
ImportExtFunctions(ar, s_functions, ClassInfo::GetSystem());
AnalysisResultPtr ar2 = AnalysisResultPtr(new AnalysisResult());
s_variables = VariableTablePtr(new VariableTable(*ar2.get()));
s_constants = ConstantTablePtr(new ConstantTable(*ar2.get()));
ImportExtFunctions(ar, ClassInfo::GetSystem());
ConstantTablePtr cns = ar->getConstants();
// load extension constants, classes and dynamics
ImportExtConstants(ar, s_constants, ClassInfo::GetSystem());
ImportExtConstants(ar, cns, ClassInfo::GetSystem());
ImportExtClasses(ar);
Array constants = ClassInfo::GetSystemConstants();
@@ -353,11 +342,11 @@ bool BuiltinSymbols::Load(AnalysisResultPtr ar) {
CVarRef key = it.first();
if (!key.isString()) continue;
std::string name = key.toCStrRef().data();
if (s_constants->getSymbol(name)) continue;
if (cns->getSymbol(name)) continue;
if (name == "true" || name == "false" || name == "null") continue;
CVarRef value = it.secondRef();
if (!value.isInitialized() || value.isObject()) continue;
ExpressionPtr e = Expression::MakeScalarExpression(ar2, ar2, loc, value);
ExpressionPtr e = Expression::MakeScalarExpression(ar, ar, loc, value);
TypePtr t =
value.isNull() ? Type::Null :
value.isBoolean() ? Type::Boolean :
@@ -365,122 +354,47 @@ bool BuiltinSymbols::Load(AnalysisResultPtr ar) {
value.isDouble() ? Type::Double :
value.isArray() ? Type::Array : Type::Variant;
s_constants->add(key.toCStrRef().data(), t, e, ar2, e);
cns->add(key.toCStrRef().data(), t, e, ar, e);
}
s_variables = ar2->getVariables();
for (int i = 0, n = NumGlobalNames(); i < n; ++i) {
s_variables->add(GlobalNames[i], Type::Variant, false, ar,
ConstructPtr(), ModifierExpressionPtr());
ar->getVariables()->add(GlobalNames[i], Type::Variant, false, ar,
ConstructPtr(), ModifierExpressionPtr());
}
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);
cns->setDynamic(ar, "PHP_BINARY", true);
cns->setDynamic(ar, "PHP_BINDIR", true);
cns->setDynamic(ar, "PHP_OS", true);
cns->setDynamic(ar, "PHP_SAPI", true);
cns->setDynamic(ar, "SID", true);
// parse all PHP files under system/php
s_systemAr = ar = AnalysisResultPtr(new AnalysisResult());
ar->loadBuiltins();
string slib = get_systemlib();
// Systemlib files were all parsed by hphp_process_init
Scanner scanner(slib.c_str(), slib.size(),
Option::GetScannerType(), "systemlib.php");
Compiler::Parser parser(scanner, "systemlib.php", ar);
if (!parser.parse()) {
Logger::Error("Unable to parse systemlib.php: %s",
parser.getMessage().c_str());
assert(false);
}
ar->analyzeProgram(true);
ar->inferTypes();
const StringToFileScopePtrMap &files = ar->getAllFiles();
for (StringToFileScopePtrMap::const_iterator iterFile = files.begin();
iterFile != files.end(); iterFile++) {
const StringToClassScopePtrVecMap &classes =
iterFile->second->getClasses();
for (StringToClassScopePtrVecMap::const_iterator iter = classes.begin();
iter != classes.end(); ++iter) {
assert(iter->second.size() == 1);
iter->second[0]->setSystem();
assert(!s_classes[iter->first]);
s_classes[iter->first] = iter->second[0];
for (const auto& file : files) {
file.second->setSystem();
const auto& classes = file.second->getClasses();
for (const auto& clsVec : classes) {
assert(clsVec.second.size() == 1);
auto cls = clsVec.second[0];
cls->setSystem();
ar->addSystemClass(cls);
for (const auto& func : cls->getFunctions()) {
FunctionScope::RecordFunctionInfo(func.first, func.second);
}
}
const StringToFunctionScopePtrMap &functions =
iterFile->second->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter = functions.begin();
iter != functions.end(); ++iter) {
iter->second->setSystem();
s_functions[iter->first] = iter->second;
const auto& functions = file.second->getFunctions();
for (const auto& func : functions) {
func.second->setSystem();
ar->addSystemFunction(func.second);
FunctionScope::RecordFunctionInfo(func.first, func.second);
}
}
return true;
}
AnalysisResultPtr BuiltinSymbols::LoadGlobalSymbols(const char *fileName) {
AnalysisResultPtr ar(new AnalysisResult());
string phpBaseName = "/system/globals/";
phpBaseName += fileName;
string phpFileName = Option::GetSystemRoot() + phpBaseName;
const char *baseName = s_strings.add(phpBaseName.c_str());
fileName = s_strings.add(phpFileName.c_str());
try {
Scanner scanner(fileName, Option::GetScannerType());
Compiler::Parser parser(scanner, baseName, ar);
if (!parser.parse()) {
assert(false);
Logger::Error("Unable to parse file %s: %s", fileName,
parser.getMessage().c_str());
}
} catch (FileOpenException &e) {
Logger::Error("%s", e.getMessage().c_str());
}
ar->analyzeProgram(true);
ar->inferTypes();
return ar;
}
void BuiltinSymbols::LoadFunctions(AnalysisResultPtr ar,
StringToFunctionScopePtrMap &functions) {
assert(Loaded);
functions.insert(s_functions.begin(), s_functions.end());
}
void BuiltinSymbols::LoadClasses(AnalysisResultPtr ar,
StringToClassScopePtrMap &classes) {
assert(Loaded);
classes.insert(s_classes.begin(), s_classes.end());
}
void BuiltinSymbols::LoadVariables(AnalysisResultPtr ar,
VariableTablePtr variables) {
assert(Loaded);
if (s_variables) {
variables->import(s_variables);
}
}
void BuiltinSymbols::LoadConstants(AnalysisResultPtr ar,
ConstantTablePtr constants) {
assert(Loaded);
if (s_constants) {
constants->import(s_constants);
}
}
ConstantTablePtr BuiltinSymbols::LoadSystemConstants() {
AnalysisResultPtr ar = LoadGlobalSymbols("constants.php");
const auto &fileScopes = ar->getAllFilesVector();
if (!fileScopes.empty()) {
return fileScopes[0]->getConstants();
}
throw std::runtime_error("LoadSystemConstants failed");
}
void BuiltinSymbols::LoadSuperGlobals() {
if (s_superGlobals.empty()) {
s_superGlobals["_SERVER"] = Type::Variant;
+7 -22
Ver Arquivo
@@ -24,16 +24,17 @@
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(Type);
DECLARE_EXTENDED_BOOST_TYPES(Type);
DECLARE_BOOST_TYPES(AnalysisResult);
DECLARE_BOOST_TYPES(FunctionScope);
DECLARE_BOOST_TYPES(ClassScope);
DECLARE_EXTENDED_BOOST_TYPES(FunctionScope);
DECLARE_EXTENDED_BOOST_TYPES(ClassScope);
DECLARE_BOOST_TYPES(VariableTable);
DECLARE_BOOST_TYPES(ConstantTable);
class BuiltinSymbols {
public:
static bool Loaded;
static AnalysisResultPtr s_systemAr;
static bool Load(AnalysisResultPtr ar);
@@ -46,11 +47,6 @@ public:
static void LoadConstants(AnalysisResultPtr ar,
ConstantTablePtr constants);
/*
* Load system/globals/constants.php.
*/
static ConstantTablePtr LoadSystemConstants();
/**
* Testing whether a variable is a PHP superglobal.
*/
@@ -60,35 +56,24 @@ public:
static bool IsDeclaredDynamic(const std::string& name);
static void LoadSuperGlobals();
static StringToFunctionScopePtrMap s_functions;
static StringToClassScopePtrMap s_classes;
static VariableTablePtr s_variables;
static ConstantTablePtr s_constants;
static AnalysisResultPtr s_systemAr;
static const char *const GlobalNames[];
static int NumGlobalNames();
private:
static StringBag s_strings;
static const char *SystemClasses[];
static AnalysisResultPtr LoadGlobalSymbols(const char *fileName);
static StringToTypePtrMap s_superGlobals;
static std::set<std::string> s_declaredDynamic;
static void *s_handle_main;
static FunctionScopePtr ImportFunctionScopePtr(AnalysisResultPtr ar,
ClassInfo *cls,
ClassInfo::MethodInfo *method);
static void ImportExtFunctions(AnalysisResultPtr ar,
StringToFunctionScopePtrMap &map,
ClassInfo *cls);
static void ImportExtFunctions(AnalysisResultPtr ar,
FunctionScopePtrVec &vec,
ClassInfo *cls);
static void ImportExtMethods(AnalysisResultPtr ar,
FunctionScopePtrVec &vec,
ClassInfo *cls);
static void ImportExtProperties(AnalysisResultPtr ar,
VariableTablePtr dest,
ClassInfo *cls);
+171 -2
Ver Arquivo
@@ -14,15 +14,16 @@
+----------------------------------------------------------------------+
*/
#include <stdarg.h>
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include <boost/format.hpp>
@@ -424,3 +425,171 @@ int CodeGenerator::ClassScopeCompare::cmp(const ClassScopeRawPtr &p1,
if (d) return d;
return strcasecmp(p1->getName().c_str(), p2->getName().c_str());
}
void CodeGenerator::printObjectHeader(const std::string className,
int numProperties) {
std::string prefixedClassName;
prefixedClassName.append(m_astPrefix);
prefixedClassName.append(className);
m_astClassNames.push_back(prefixedClassName);
printf("O:%d:\"%s\":%d:{",
(int)prefixedClassName.length(), prefixedClassName.c_str(), numProperties);
}
void CodeGenerator::printObjectFooter() {
printf("}");
m_astClassNames.pop_back();
}
void CodeGenerator::printPropertyHeader(const std::string propertyName) {
auto prefixedClassName = m_astClassNames.back();
auto len = 2+prefixedClassName.length()+propertyName.length();
printf("s:%d:\"", (int)len);
*m_out << (char)0;
printf("%s", prefixedClassName.c_str());
*m_out << (char)0;
printf("%s\";", propertyName.c_str());
}
void CodeGenerator::printNull() {
printf("N;");
}
void CodeGenerator::printBool(bool value) {
printf("b:%d;", value ? 1 : 0);
}
void CodeGenerator::printValue(double v) {
*m_out << "d:";
if (std::isnan(v)) {
*m_out << "NAN";
} else if (std::isinf(v)) {
if (v < 0) *m_out << '-';
*m_out << "INF";
} else {
char *buf;
if (v == 0.0) v = 0.0; // so to avoid "-0" output
vspprintf(&buf, 0, "%.*H", 14, v);
m_out->write(buf, strlen(buf));
free(buf);
}
*m_out << ';';
}
void CodeGenerator::printValue(int32_t value) {
printf("i:%d;", value);
}
void CodeGenerator::printValue(int64_t value) {
printf("i:%" PRId64 ";", value);
}
void CodeGenerator::printValue(std::string value) {
printf("s:%d:\"", (int)value.length());
getStream()->write(value.c_str(), value.length());
printf("\";");
}
void CodeGenerator::printModifierVector(std::string value) {
printf("V:9:\"HH\\Vector\":1:{");
printObjectHeader("Modifier", 1);
printPropertyHeader("name");
printValue(value);
printObjectFooter();
printf("}");
}
void CodeGenerator::printTypeExpression(std::string value) {
printObjectHeader("TypeExpression", 1);
printPropertyHeader("name");
printValue(value);
printObjectFooter();
}
void CodeGenerator::printExpression(ExpressionPtr expression, bool isRef) {
if (isRef) {
printObjectHeader("UnaryOpExpression", 3);
printPropertyHeader("expression");
expression->outputCodeModel(*this);
printPropertyHeader("operation");
printValue(PHP_REFERENCE_OP);
printPropertyHeader("sourceLocation");
printLocation(expression->getLocation());
printObjectFooter();
} else {
expression->outputCodeModel(*this);
}
}
void CodeGenerator::printExpressionVector(ExpressionListPtr el) {
auto count = el == nullptr ? 0 : el->getCount();
printf("V:9:\"HH\\Vector\":%d:{", count);
if (count > 0) {
el->outputCodeModel(*this);
}
printf("}");
}
void CodeGenerator::printExpressionVector(ExpressionPtr e) {
if (e->is(Expression::KindOfExpressionList)) {
auto sl = static_pointer_cast<ExpressionList>(e);
printExpressionVector(sl);
} else {
printf("V:9:\"HH\\Vector\":1:{");
e->outputCodeModel(*this);
printf("}");
}
}
void CodeGenerator::printAsBlock(StatementPtr s) {
if (s != nullptr && s->is(Statement::KindOfBlockStatement)) {
s->outputCodeModel(*this);
} else {
auto numProps = s == nullptr ? 1 : 2;
printObjectHeader("BlockStatement", numProps);
printPropertyHeader("statements");
printStatementVector(s);
if (s != nullptr) {
printPropertyHeader("sourceLocation");
printLocation(s->getLocation());
}
printObjectFooter();
}
}
void CodeGenerator::printStatementVector(StatementListPtr sl) {
printf("V:9:\"HH\\Vector\":%d:{", sl->getCount());
if (sl->getCount() > 0) {
sl->outputCodeModel(*this);
}
printf("}");
}
void CodeGenerator::printStatementVector(StatementPtr s) {
if (s == nullptr) {
printf("V:9:\"HH\\Vector\":0:{}");
} else if (s->is(Statement::KindOfStatementList)) {
auto sl = static_pointer_cast<StatementList>(s);
printStatementVector(sl);
} else {
printf("V:9:\"HH\\Vector\":1:{");
s->outputCodeModel(*this);
printf("}");
}
}
void CodeGenerator::printLocation(LocationPtr location) {
if (location == nullptr) return;
printObjectHeader("SourceLocation", 4);
printPropertyHeader("startLine");
printValue(location->line0);
printPropertyHeader("endLine");
printValue(location->line1);
printPropertyHeader("startColumn");
printValue(location->char0);
printPropertyHeader("endColumn");
printValue(location->char1);
printObjectFooter();
}
+31 -1
Ver Arquivo
@@ -24,12 +24,16 @@ namespace HPHP {
DECLARE_BOOST_TYPES(AnalysisResult);
DECLARE_BOOST_TYPES(Statement);
DECLARE_BOOST_TYPES(StatementList);
DECLARE_BOOST_TYPES(Construct);
DECLARE_BOOST_TYPES(BlockScope);
DECLARE_BOOST_TYPES(ClassScope);
DECLARE_EXTENDED_BOOST_TYPES(ClassScope);
DECLARE_BOOST_TYPES(FunctionScope);
DECLARE_BOOST_TYPES(FileScope);
DECLARE_BOOST_TYPES(LoopStatement);
DECLARE_BOOST_TYPES(Location);
DECLARE_BOOST_TYPES(Expression);
DECLARE_BOOST_TYPES(ExpressionList);
class CodeGenerator {
public:
@@ -45,6 +49,7 @@ public:
SystemCPP, // special mode for generating builtin classes
TextHHBC, // HHBC dump in human-readable format
BinaryHHBC, // serialized HHBC
CodeModel, // serialized Code Model classes
};
enum Stream {
@@ -265,12 +270,37 @@ public:
FileScopeRawPtr getLiteralScope() const {
return m_literalScope;
}
/**
* Support for printing AST nodes in PHP serialize() format.
*/
void printObjectHeader(const std::string className, int numProperties);
void printPropertyHeader(const std::string propertyName);
void printObjectFooter();
void printNull();
void printBool(bool value);
void printValue(double value);
void printValue(int32_t value);
void printValue(int64_t value);
void printValue(std::string value);
void printModifierVector(std::string value);
void printTypeExpression(std::string value);
void printExpression(ExpressionPtr expression, bool isRef);
void printExpressionVector(ExpressionListPtr el);
void printExpressionVector(ExpressionPtr e);
void printAsBlock(StatementPtr s);
void printStatementVector(StatementListPtr sl);
void printStatementVector(StatementPtr s);
void printLocation(LocationPtr location);
void setAstClassPrefix(const std::string &prefix) { m_astPrefix = prefix; }
private:
std::string m_filename;
Stream m_curStream;
std::ostream *m_streams[StreamCount];
std::ostream *m_out;
Output m_output;
std::string m_astPrefix;
std::vector<std::string> m_astClassNames;
bool m_verbose;
int m_indentation[StreamCount];
+117
Ver Arquivo
@@ -0,0 +1,117 @@
/*
+----------------------------------------------------------------------+
| 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. |
+----------------------------------------------------------------------+
*/
// This file is @generated by tools/code-model/GenerateEnums.sh
#ifndef incl_HPHP_CODE_MODEL_ENUMS_H_
#define incl_HPHP_CODE_MODEL_ENUMS_H_
namespace HPHP {
/** The kinds of operations that IBinaryOpExpressions can perform. */
enum CodeModelBinaryOperator {
PHP_AND_ASSIGN = 1,
PHP_AND = 2,
PHP_ARRAY_ELEMENT = 3,
PHP_ARRAY_PAIR = 4,
PHP_ASSIGNMENT = 5,
PHP_BOOLEAN_AND = 6,
PHP_BOOLEAN_OR = 7,
PHP_CAST = 8,
PHP_CONCAT_ASSIGN = 9,
PHP_CONCAT = 10,
PHP_DIVIDE_ASSIGN = 11,
PHP_DIVIDE = 12,
PHP_INSTANCEOF = 13,
PHP_IS_EQUAL = 14,
PHP_IS_GREATER = 15,
PHP_IS_GREATER_OR_EQUAL = 16,
PHP_IS_IDENTICAL = 17,
PHP_IS_NOT_IDENTICAL = 18,
PHP_IS_NOT_EQUAL = 19,
PHP_IS_SMALLER = 20,
PHP_IS_SMALLER_OR_EQUAL = 21,
PHP_LOGICAL_AND = 22,
PHP_LOGICAL_OR = 23,
PHP_LOGICAL_XOR = 24,
PHP_MINUS_ASSIGN = 25,
PHP_MINUS = 26,
PHP_MODULUS_ASSIGN = 27,
PHP_MODULUS = 28,
PHP_MULTIPLY_ASSIGN = 29,
PHP_MULTIPLY = 30,
PHP_OR_ASSIGN = 31,
PHP_OR = 32,
PHP_PLUS_ASSIGN = 33,
PHP_PLUS = 34,
PHP_SHIFT_LEFT_ASSIGN = 35,
PHP_SHIFT_LEFT = 36,
PHP_SHIFT_RIGHT_ASSIGN = 37,
PHP_SHIFT_RIGHT = 38,
PHP_XOR_ASSIGN = 39,
PHP_XOR = 40,
};
/** The kinds of operations that IUnaryOpExpressions can perform. */
enum CodeModelUnaryOperator {
PHP_ARRAY_CAST_OP = 1,
PHP_ARRAY_APPEND_POINT_OP = 2,
PHP_AWAIT_OP = 3,
PHP_BOOL_CAST_OP = 4,
PHP_BITWISE_NOT_OP = 5,
PHP_CLONE_OP = 6,
PHP_DYNAMIC_VARIABLE_OP = 7,
PHP_ERROR_CONTROL_OP = 8,
PHP_FLOAT_CAST_OP = 9,
PHP_INCLUDE_OP = 10,
PHP_INCLUDE_ONCE_OP = 11,
PHP_INT_CAST_OP = 12,
PHP_MINUS_OP = 13,
PHP_NOT_OP = 14,
PHP_OBJECT_CAST_OP = 15,
PHP_PLUS_OP = 16,
PHP_POST_DECREMENT_OP = 17,
PHP_POST_INCREMENT_OP = 18,
PHP_PRE_DECREMENT_OP = 19,
PHP_PRE_INCREMENT_OP = 20,
PHP_PRINT_OP = 21,
PHP_REFERENCE_OP = 22,
PHP_REQUIRE_OP = 23,
PHP_REQUIRE_ONCE_OP = 24,
PHP_STRING_CAST_OP = 25,
PHP_UNSET_CAST_OP = 26,
};
/** Enumerates the kinds of trait require statements. */
enum CodeModelRequireKind {
PHP_EXTENDS = 1,
PHP_IMPLEMENTS = 2,
};
/** Enumerates the kinds of type declaration statements. */
enum CodeModelTypeKind {
PHP_CLASS = 1,
PHP_INTERFACE = 2,
PHP_TRAIT = 3,
};
/** The sort order to use when grouping query results */
enum CodeModelOrder {
PHP_NOT_SPECIFIED = 1,
PHP_ASCENDING = 2,
PHP_DESCENDING = 3,
};
}
#endif // incl_HPHP_CODE_MODEL_ENUMS_H_
+16 -6
Ver Arquivo
@@ -25,7 +25,7 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
#include "hphp/util/logger.h"
#include "hphp/util/db-conn.h"
#include "hphp/util/exception.h"
@@ -344,8 +344,8 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
return 1;
}
if (vm.count("version")) {
#ifdef HPHP_VERSION
#undef HPHP_VERSION
#ifdef HHVM_VERSION
#undef HHVM_VERSION
#endif
#ifdef HPHP_COMPILER_STR
@@ -358,7 +358,7 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
#define HPHP_COMPILER_STR "HipHop Compiler v"
#endif
#define HPHP_VERSION(v) cout << HPHP_COMPILER_STR #v << "\n";
#define HHVM_VERSION(v) cout << HPHP_COMPILER_STR #v << "\n";
#include "../version" // nolint
cout << "Compiler: " << kCompilerId << "\n";
@@ -484,6 +484,8 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
Option::ParseTimeOpts = false;
}
initialize_hhbbc_options();
return 0;
}
@@ -540,6 +542,12 @@ int process(const CompilerOptions &po) {
bool isPickledPHP = (po.target == "php" && po.format == "pickled");
if (!isPickledPHP) {
bool wp = Option::WholeProgram;
Option::WholeProgram = false;
BuiltinSymbols::s_systemAr = ar;
hphp_process_init();
BuiltinSymbols::s_systemAr.reset();
Option::WholeProgram = wp;
if (po.target == "hhbc" && !Option::WholeProgram) {
// We're trying to produce the same bytecode as runtime parsing.
// There's nothing to do.
@@ -547,9 +555,7 @@ int process(const CompilerOptions &po) {
if (!BuiltinSymbols::Load(ar)) {
return false;
}
ar->loadBuiltins();
}
hphp_process_init();
}
{
@@ -596,6 +602,7 @@ int process(const CompilerOptions &po) {
return 1;
}
if (Option::WholeProgram || po.target == "analyze") {
Timer timer(Timer::WallTime, "analyzeProgram");
ar->analyzeProgram();
}
}
@@ -800,6 +807,7 @@ void hhbcTargetInit(const CompilerOptions &po, AnalysisResultPtr ar) {
if (po.format.find("exe") != string::npos) {
RuntimeOption::RepoCentralPath += ".hhbc";
}
unlink(RuntimeOption::RepoCentralPath.c_str());
RuntimeOption::RepoLocalMode = "--";
RuntimeOption::RepoDebugInfo = Option::RepoDebugInfo;
RuntimeOption::RepoJournal = "memory";
@@ -915,6 +923,8 @@ int runTarget(const CompilerOptions &po) {
cmd += buf;
cmd += " -vRepo.Authoritative=true";
if (getenv("HPHP_DUMP_BYTECODE")) cmd += " -vEval.DumpBytecode=1";
if (getenv("HPHP_INTERP")) cmd += " -vEval.Jit=0";
cmd += " -vRepo.Local.Mode=r- -vRepo.Local.Path=";
}
cmd += po.outputDir + '/' + po.program;
+15 -1
Ver Arquivo
@@ -469,9 +469,23 @@ void Construct::parseTimeFatal(Compiler::ErrorType err, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
string msg;
Util::string_vsnprintf(msg, fmt, ap);
string_vsnprintf(msg, fmt, ap);
va_end(ap);
if (err != Compiler::NoError) Compiler::Error(err, shared_from_this());
throw ParseTimeFatalException(m_loc->file, m_loc->line0, "%s", msg.c_str());
}
void Construct::analysisTimeFatal(Compiler::ErrorType err,
const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
string msg;
string_vsnprintf(msg, fmt, ap);
va_end(ap);
assert(err != Compiler::NoError);
Compiler::Error(err, shared_from_this());
throw AnalysisTimeFatalException(m_loc->file, m_loc->line0,
"%s [analysis]", msg.c_str());
}
+10 -7
Ver Arquivo
@@ -17,7 +17,7 @@
#ifndef incl_HPHP_CONSTRUCT_H_
#define incl_HPHP_CONSTRUCT_H_
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/block_scope.h"
@@ -166,10 +166,6 @@ 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 {
@@ -184,6 +180,8 @@ public:
void resetScope(BlockScopeRawPtr scope, bool resetOrigScope=false);
void parseTimeFatal(Compiler::ErrorType error, const char *fmt, ...)
ATTRIBUTE_PRINTF(3,4);
void analysisTimeFatal(Compiler::ErrorType error, const char *fmt, ...)
ATTRIBUTE_PRINTF(3,4);
virtual int getLocalEffects() const { return UnknownEffect;}
int getChildrenEffects() const;
int getContainedEffects() const;
@@ -199,7 +197,8 @@ public:
}
template<typename T>
std::shared_ptr<T> Clone(std::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);
@@ -247,6 +246,11 @@ public:
const AstWalkerStateVec &start,
ConstructPtr endBefore, ConstructPtr endAfter);
/**
* Generates a serialized Code Model corresponding to this AST.
*/
virtual void outputCodeModel(CodeGenerator &cg) = 0;
/**
* Called when generating code.
*/
@@ -299,7 +303,6 @@ 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:
@@ -19,6 +19,7 @@
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/static_member_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
@@ -388,6 +389,42 @@ ExpressionPtr ArrayElementExpression::unneeded() {
return Expression::unneeded();
}
///////////////////////////////////////////////////////////////////////////////
void ArrayElementExpression::outputCodeModel(CodeGenerator &cg) {
if (Option::ConvertSuperGlobals && m_global && !m_dynamicGlobal &&
getScope() && (getScope()->is(BlockScope::ProgramScope) ||
getScope()-> getVariables()->
isConvertibleSuperGlobal(m_globalName))) {
cg.printObjectHeader("SimpleVariableExpression", 2);
cg.printPropertyHeader("name");
cg.printValue(m_globalName);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
} else if (m_offset) {
cg.printObjectHeader("BinaryOpExpression", 4);
cg.printPropertyHeader("expression1");
m_variable->outputCodeModel(cg);
cg.printPropertyHeader("expression2");
cg.printExpression(m_offset, false);
cg.printPropertyHeader("operation");
cg.printValue(PHP_ARRAY_ELEMENT);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
} else {
cg.printObjectHeader("UnaryOpExpression", 3);
cg.printPropertyHeader("expression");
m_variable->outputCodeModel(cg);
cg.printPropertyHeader("operation");
cg.printValue(PHP_ARRAY_APPEND_POINT_OP);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -17,6 +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/compiler/code_model_enums.h"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -122,6 +123,25 @@ bool ArrayPairExpression::canonCompare(ExpressionPtr e) const {
return m_ref == a->m_ref;
}
///////////////////////////////////////////////////////////////////////////////
void ArrayPairExpression::outputCodeModel(CodeGenerator &cg) {
if (m_name) {
cg.printObjectHeader("BinaryOpExpression", 4);
cg.printPropertyHeader("expression1");
m_name->outputCodeModel(cg);
cg.printPropertyHeader("expression2");
cg.printExpression(m_value, m_ref);
cg.printPropertyHeader("operation");
cg.printValue(PHP_ARRAY_PAIR);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
} else {
cg.printExpression(m_value, m_ref);
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -26,6 +26,7 @@
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
@@ -306,6 +307,21 @@ TypePtr AssignmentExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return inferAssignmentTypes(ar, type, coerce, m_variable, m_value);
}
///////////////////////////////////////////////////////////////////////////////
void AssignmentExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("BinaryOpExpression", 4);
cg.printPropertyHeader("expression1");
m_variable->outputCodeModel(cg);
cg.printPropertyHeader("expression2");
cg.printExpression(m_value, m_ref);
cg.printPropertyHeader("operation");
cg.printValue(PHP_ASSIGNMENT);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -16,6 +16,7 @@
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/code_model_enums.h"
using namespace HPHP;
@@ -82,6 +83,18 @@ TypePtr AwaitExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return Type::Variant;
}
///////////////////////////////////////////////////////////////////////////////
void AwaitExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("UnaryOpExpression", 3);
cg.printPropertyHeader("expression");
m_exp->outputCodeModel(cg);
cg.printPropertyHeader("operation");
cg.printValue(PHP_AWAIT_OP);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -21,6 +21,7 @@
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
@@ -32,6 +33,7 @@
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/statement/loop_statement.h"
#include "hphp/runtime/base/tv-arith.h"
#include "hphp/runtime/vm/runtime.h"
using namespace HPHP;
@@ -65,7 +67,7 @@ BinaryOpExpression::BinaryOpExpression
break;
case T_COLLECTION: {
std::string s = m_exp1->getLiteralString();
int cType = 0;
Collection::Type cType = Collection::InvalidType;
if (strcasecmp(s.c_str(), "vector") == 0) {
cType = Collection::VectorType;
} else if (strcasecmp(s.c_str(), "map") == 0) {
@@ -76,6 +78,12 @@ BinaryOpExpression::BinaryOpExpression
cType = Collection::SetType;
} else if (strcasecmp(s.c_str(), "pair") == 0) {
cType = Collection::PairType;
} else if (strcasecmp(s.c_str(), "frozenvector") == 0) {
cType = Collection::FrozenVectorType;
} else if (strcasecmp(s.c_str(), "frozenmap") == 0) {
cType = Collection::FrozenMapType;
} else if (strcasecmp(s.c_str(), "frozenset") == 0) {
cType = Collection::FrozenSetType;
}
ExpressionListPtr el = static_pointer_cast<ExpressionList>(m_exp2);
el->setCollectionType(cType);
@@ -476,6 +484,9 @@ ExpressionPtr BinaryOpExpression::foldConst(AnalysisResultConstPtr ar) {
ExpressionPtr aExp = m_exp1;
ExpressionPtr bExp = binOpExp->m_exp1;
ExpressionPtr cExp = binOpExp->m_exp2;
if (aExp->isArray() || bExp->isArray() || cExp->isArray()) {
break;
}
m_exp1 = binOpExp = Clone(binOpExp);
m_exp2 = cExp;
binOpExp->m_exp1 = aExp;
@@ -536,6 +547,9 @@ ExpressionPtr BinaryOpExpression::foldConst(AnalysisResultConstPtr ar) {
*result.asCell() = cellBitXor(*v1.asCell(), *v2.asCell());
break;
case '.':
if (v1.isArray() || v2.isArray()) {
return ExpressionPtr();
}
result = concat(v1.toString(), v2.toString());
break;
case T_IS_IDENTICAL:
@@ -802,7 +816,7 @@ TypePtr BinaryOpExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
case T_COLLECTION:
et1 = Type::Any;
et2 = Type::Any;
rt = Type::Object;
rt = Type::CreateObjectType(m_exp1->getLiteralString());
break;
default:
assert(false);
@@ -911,6 +925,76 @@ TypePtr BinaryOpExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return rt;
}
///////////////////////////////////////////////////////////////////////////////
void BinaryOpExpression::outputCodeModel(CodeGenerator &cg) {
if (m_op == T_COLLECTION) {
cg.printObjectHeader("CollectionInitializerExpression", 3);
cg.printPropertyHeader("collection");
m_exp1->outputCodeModel(cg);
cg.printPropertyHeader("arguments");
cg.printExpressionVector(static_pointer_cast<ExpressionList>(m_exp2));
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
return;
}
cg.printObjectHeader("BinaryOpExpression", 4);
cg.printPropertyHeader("expression1");
m_exp1->outputCodeModel(cg);
cg.printPropertyHeader("expression2");
m_exp2->outputCodeModel(cg);
cg.printPropertyHeader("operation");
int op = 0;
switch (m_op) {
case T_PLUS_EQUAL: op = PHP_PLUS_ASSIGN; break;
case T_MINUS_EQUAL: op = PHP_MINUS_ASSIGN; break;
case T_MUL_EQUAL: op = PHP_MULTIPLY_ASSIGN; break;
case T_DIV_EQUAL: op = PHP_DIVIDE_ASSIGN; break;
case T_CONCAT_EQUAL: op = PHP_CONCAT_ASSIGN; break;
case T_MOD_EQUAL: op = PHP_MODULUS_ASSIGN; break;
case T_AND_EQUAL: op = PHP_AND_ASSIGN; break;
case T_OR_EQUAL: op = PHP_OR_ASSIGN; break;
case T_XOR_EQUAL: op = PHP_XOR_ASSIGN; break;
case T_SL_EQUAL: op = PHP_SHIFT_LEFT_ASSIGN; break;
case T_SR_EQUAL: op = PHP_SHIFT_RIGHT_ASSIGN; break;
case T_BOOLEAN_OR: op = PHP_BOOLEAN_OR; break;
case T_BOOLEAN_AND: op = PHP_BOOLEAN_AND; break;
case T_LOGICAL_OR: op = PHP_LOGICAL_OR; break;
case T_LOGICAL_AND: op = PHP_LOGICAL_AND; break;
case T_LOGICAL_XOR: op = PHP_LOGICAL_XOR; break;
case '|': op = PHP_OR; break;
case '&': op = PHP_AND; break;
case '^': op = PHP_XOR; break;
case '.': op = PHP_CONCAT; break;
case '+': op = PHP_PLUS; break;
case '-': op = PHP_MINUS; break;
case '*': op = PHP_MULTIPLY; break;
case '/': op = PHP_DIVIDE; break;
case '%': op = PHP_MODULUS; break;
case T_SL: op = PHP_SHIFT_LEFT; break;
case T_SR: op = PHP_SHIFT_RIGHT; break;
case T_IS_IDENTICAL: op = PHP_IS_IDENTICAL; break;
case T_IS_NOT_IDENTICAL: op = PHP_IS_NOT_IDENTICAL; break;
case T_IS_EQUAL: op = PHP_IS_EQUAL; break;
case T_IS_NOT_EQUAL: op = PHP_IS_NOT_EQUAL; break;
case '<': op = PHP_IS_SMALLER; break;
case T_IS_SMALLER_OR_EQUAL: op = PHP_IS_SMALLER_OR_EQUAL; break;
case '>': op = PHP_IS_GREATER; break;
case T_IS_GREATER_OR_EQUAL: op = PHP_IS_GREATER_OR_EQUAL; break;
case T_INSTANCEOF: op = PHP_INSTANCEOF; break;
default:
assert(false);
}
cg.printValue(op);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -991,4 +1075,3 @@ bool BinaryOpExpression::isOpEqual() {
}
return false;
}
@@ -221,6 +221,18 @@ bool ClassConstantExpression::canonCompare(ExpressionPtr e) const {
m_className == static_cast<ClassConstantExpression*>(e.get())->m_className;
}
///////////////////////////////////////////////////////////////////////////////
void ClassConstantExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("ClassPropertyExpression", 3);
cg.printPropertyHeader("className");
StaticClassName::outputCodeModel(cg);
cg.printPropertyHeader("propertyName");
cg.printValue(m_varName);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -46,6 +46,7 @@ public:
bool isValid() const { return m_valid; }
bool isDynamic() const;
bool hasClass() const { return m_defScope != 0; }
bool isColonColonClass() const { return m_varName == "class"; }
private:
std::string m_varName;
BlockScope *m_defScope;
+203 -102
Ver Arquivo
@@ -13,8 +13,11 @@
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/closure_expression.h"
#include <boost/make_shared.hpp>
#include "folly/ScopeGuard.h"
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/simple_variable.h"
@@ -24,68 +27,79 @@
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
using namespace HPHP;
namespace HPHP {
//////////////////////////////////////////////////////////////////////
TypePtr ClosureExpression::s_ClosureType =
Type::CreateObjectType("closure"); // needs lower case
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
ClosureExpression::ClosureExpression(
EXPRESSION_CONSTRUCTOR_PARAMETERS,
ClosureType type,
FunctionStatementPtr func,
ExpressionListPtr vars)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ClosureExpression))
, m_type(type)
, m_func(func)
, m_captureState(m_type == ClosureType::Short ? CaptureState::Unknown
: CaptureState::Known)
{
switch (m_type) {
case ClosureType::Short:
break;
case ClosureType::Long:
if (vars) initializeFromUseList(vars);
break;
}
}
ClosureExpression::ClosureExpression
(EXPRESSION_CONSTRUCTOR_PARAMETERS, FunctionStatementPtr func,
ExpressionListPtr vars)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ClosureExpression)),
m_func(func) {
void ClosureExpression::initializeFromUseList(ExpressionListPtr vars) {
m_vars = ExpressionListPtr(
new ExpressionList(vars->getScope(), vars->getLocation()));
if (vars) {
m_vars = ExpressionListPtr
(new ExpressionList(vars->getScope(), vars->getLocation()));
// push the vars in reverse order, not retaining duplicates
std::set<string> seenBefore;
// Because PHP is insane you can have a use variable with the same
// name as a param name.
// In that case, params win (which is different than zend but much easier)
auto seenBefore = collectParamNames();
// Because PHP is insane you can have a use variable with the same
// name as a param name.
// In that case, params win (which is different than zend but much easier)
ExpressionListPtr bodyParams = m_func->getParams();
if (bodyParams) {
int nParams = bodyParams->getCount();
for (int i = 0; i < nParams; i++) {
ParameterExpressionPtr par(
static_pointer_cast<ParameterExpression>((*bodyParams)[i]));
seenBefore.insert(par->getName());
}
for (int i = vars->getCount() - 1; i >= 0; i--) {
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;
}
for (int i = vars->getCount() - 1; i >= 0; i--) {
ParameterExpressionPtr param(
dynamic_pointer_cast<ParameterExpression>((*vars)[i]));
assert(param);
if (seenBefore.find(param->getName().c_str()) == seenBefore.end()) {
seenBefore.insert(param->getName().c_str());
m_vars->insertElement(param);
}
}
if (m_vars) {
m_values = ExpressionListPtr
(new ExpressionList(m_vars->getScope(), m_vars->getLocation()));
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
SimpleVariablePtr var(new SimpleVariable(param->getScope(),
param->getLocation(),
name));
if (param->isRef()) {
var->setContext(RefValue);
}
m_values->addElement(var);
}
assert(m_vars->getCount() == m_values->getCount());
if (seenBefore.find(param->getName().c_str()) == seenBefore.end()) {
seenBefore.insert(param->getName().c_str());
m_vars->insertElement(param);
}
}
initializeValuesFromVars();
}
void ClosureExpression::initializeValuesFromVars() {
if (!m_vars) return;
m_values = ExpressionListPtr
(new ExpressionList(m_vars->getScope(), m_vars->getLocation()));
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
SimpleVariablePtr var(new SimpleVariable(param->getScope(),
param->getLocation(),
name));
if (param->isRef()) {
var->setContext(RefValue);
}
m_values->addElement(var);
}
assert(m_vars->getCount() == m_values->getCount());
}
ExpressionPtr ClosureExpression::clone() {
@@ -132,62 +146,65 @@ void ClosureExpression::setNthKid(int n, ConstructPtr cp) {
void ClosureExpression::analyzeProgram(AnalysisResultPtr ar) {
m_func->analyzeProgram(ar);
if (m_vars) {
m_values->analyzeProgram(ar);
if (ar->getPhase() == AnalysisResult::AnalyzeAll) {
getFunctionScope()->addUse(m_func->getFunctionScope(),
BlockScope::UseKindClosure);
m_func->getFunctionScope()->setClosureVars(m_vars);
if (m_vars) analyzeVars(ar);
// closure function's variable table (not containing function's)
VariableTablePtr variables = m_func->getFunctionScope()->getVariables();
VariableTablePtr containing = getFunctionScope()->getVariables();
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
{
Symbol *containingSym = containing->addDeclaredSymbol(name, param);
containingSym->setPassClosureVar();
Symbol *sym = variables->addDeclaredSymbol(name, param);
sym->setClosureVar();
sym->setDeclaration(ConstructPtr());
if (param->isRef()) {
sym->setRefClosureVar();
sym->setUsed();
} else {
sym->clearRefClosureVar();
sym->clearUsed();
}
}
}
return;
}
if (ar->getPhase() == AnalysisResult::AnalyzeFinal) {
// closure function's variable table (not containing function's)
VariableTablePtr variables = m_func->getFunctionScope()->getVariables();
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
// so we can assign values to them, instead of seeing CVarRef
Symbol *sym = variables->getSymbol(name);
if (sym && sym->isParameter()) {
sym->setLvalParam();
}
}
}
}
FunctionScopeRawPtr container =
FunctionScopeRawPtr container =
getFunctionScope()->getContainingNonClosureFunction();
if (container && container->isStatic()) {
m_func->getModifiers()->add(T_STATIC);
}
}
void ClosureExpression::analyzeVars(AnalysisResultPtr ar) {
m_values->analyzeProgram(ar);
if (ar->getPhase() == AnalysisResult::AnalyzeAll) {
getFunctionScope()->addUse(m_func->getFunctionScope(),
BlockScope::UseKindClosure);
m_func->getFunctionScope()->setClosureVars(m_vars);
// closure function's variable table (not containing function's)
VariableTablePtr variables = m_func->getFunctionScope()->getVariables();
VariableTablePtr containing = getFunctionScope()->getVariables();
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
{
Symbol *containingSym = containing->addDeclaredSymbol(name, param);
containingSym->setPassClosureVar();
Symbol *sym = variables->addDeclaredSymbol(name, param);
sym->setClosureVar();
sym->setDeclaration(ConstructPtr());
if (param->isRef()) {
sym->setRefClosureVar();
sym->setUsed();
} else {
sym->clearRefClosureVar();
sym->clearUsed();
}
}
}
return;
}
if (ar->getPhase() == AnalysisResult::AnalyzeFinal) {
// closure function's variable table (not containing function's)
VariableTablePtr variables = m_func->getFunctionScope()->getVariables();
for (int i = 0; i < m_vars->getCount(); i++) {
ParameterExpressionPtr param =
dynamic_pointer_cast<ParameterExpression>((*m_vars)[i]);
const string &name = param->getName();
// so we can assign values to them, instead of seeing CVarRef
Symbol *sym = variables->getSymbol(name);
if (sym && sym->isParameter()) {
sym->setLvalParam();
}
}
}
}
TypePtr ClosureExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
@@ -251,6 +268,72 @@ TypePtr ClosureExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return s_ClosureType;
}
void ClosureExpression::setCaptureList(
AnalysisResultPtr ar,
const std::set<std::string>& captureNames) {
assert(m_captureState == CaptureState::Unknown);
m_captureState = CaptureState::Known;
bool usedThis = false;
SCOPE_EXIT {
/*
* TODO: closures in a non-class scope should be neither static
* nor non-static, but right now we don't really have this idea.
*
* This would allow not having to check for a $this or late bound
* class in the closure object or on the ActRec when returning
* from those closures.
*
* (We could also mark closures that don't use late static binding
* with this flag to avoid checks on closures in member functions
* when they use neither $this nor static::)
*/
if (!usedThis) m_func->getModifiers()->add(T_STATIC);
};
if (captureNames.empty()) return;
m_vars = ExpressionListPtr(
new ExpressionList(getOriginalScope(), getLocation()));
for (auto const& name : captureNames) {
if (name == "this") {
usedThis = true;
continue;
}
auto expr = ParameterExpressionPtr(new ParameterExpression(
BlockScopePtr(getOriginalScope()),
getLocation(),
TypeAnnotationPtr(),
true /* hhType */,
name,
false /* ref */,
0 /* token modifier thing */,
ExpressionPtr(),
ExpressionPtr()
));
m_vars->insertElement(expr);
}
initializeValuesFromVars();
analyzeVars(ar);
}
std::set<std::string> ClosureExpression::collectParamNames() const {
std::set<std::string> ret;
auto bodyParams = m_func->getParams();
if (!bodyParams) return ret;
int nParams = bodyParams->getCount();
for (int i = 0; i < nParams; i++) {
auto par = static_pointer_cast<ParameterExpression>((*bodyParams)[i]);
ret.insert(par->getName());
}
return ret;
}
bool ClosureExpression::hasStaticLocals() {
ConstructPtr cons(m_func);
return hasStaticLocalsImpl(cons);
@@ -279,6 +362,22 @@ bool ClosureExpression::hasStaticLocalsImpl(ConstructPtr root) {
return false;
}
///////////////////////////////////////////////////////////////////////////////
void ClosureExpression::outputCodeModel(CodeGenerator &cg) {
auto numProps = m_vars != nullptr && m_vars->getCount() > 0 ? 3 : 2;
cg.printObjectHeader("ClosureExpression", numProps);
cg.printPropertyHeader("ffunction");
m_func->outputCodeModel(cg);
if (m_vars != nullptr && m_vars->getCount() > 0) {
cg.printPropertyHeader("capturedVariables");
cg.printExpressionVector(m_vars);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -291,3 +390,5 @@ void ClosureExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
}
m_func->outputPHPBody(cg, ar);
}
}
+34 -5
Ver Arquivo
@@ -18,6 +18,7 @@
#define incl_HPHP_CLOSURE_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/parser/parser.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -29,10 +30,20 @@ DECLARE_BOOST_TYPES(ExpressionList);
class ClosureExpression : public Expression {
public:
ClosureExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
FunctionStatementPtr func, ExpressionListPtr vars);
ClosureType type,
FunctionStatementPtr func,
ExpressionListPtr vars);
DECLARE_BASE_EXPRESSION_VIRTUAL_FUNCTIONS;
// Flag for whether we have already determined the capture list for
// this lambda.
enum class CaptureState {
Unknown,
Known,
};
CaptureState captureState() const { return m_captureState; }
virtual ConstructPtr getNthKid(int n) const;
virtual void setNthKid(int n, ConstructPtr cp);
virtual int getKidCount() const;
@@ -43,17 +54,35 @@ public:
StringData* getClosureClassName() { return m_closureClassName; }
void setClosureClassName(StringData* value) { m_closureClassName = value; }
bool hasStaticLocals();
ClosureType type() const { return m_type; }
std::set<std::string> collectParamNames() const;
/*
* Initialize the capture list for a closure that uses automatic
* captures.
*
* Pre: captureState() == CaptureState::Unknown.
*/
void setCaptureList(AnalysisResultPtr ar,
const std::set<std::string>&);
private:
static TypePtr s_ClosureType;
private:
void initializeFromUseList(ExpressionListPtr vars);
void initializeValuesFromVars();
void analyzeVars(AnalysisResultPtr);
bool hasStaticLocalsImpl(ConstructPtr root);
private:
ClosureType m_type;
FunctionStatementPtr m_func;
ExpressionListPtr m_vars;
ExpressionListPtr m_values;
StringData* m_closureClassName;
static TypePtr s_ClosureType;
bool hasStaticLocalsImpl(ConstructPtr root);
std::set<std::string> m_unboundNames;
CaptureState m_captureState;
};
///////////////////////////////////////////////////////////////////////////////
@@ -273,6 +273,17 @@ TypePtr ConstantExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return actualType;
}
///////////////////////////////////////////////////////////////////////////////
void ConstantExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("SimpleVariableExpression", 2);
cg.printPropertyHeader("variableName");
cg.printValue(m_origName);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -113,6 +113,26 @@ TypePtr DynamicFunctionCall::inferTypes(AnalysisResultPtr ar, TypePtr type,
return Type::Variant;
}
///////////////////////////////////////////////////////////////////////////////
void DynamicFunctionCall::outputCodeModel(CodeGenerator &cg) {
if (m_class || !m_className.empty()) {
cg.printObjectHeader("ClassMethodCallExpression", 4);
cg.printPropertyHeader("className");
StaticClassName::outputCodeModel(cg);
cg.printPropertyHeader("methodExpression");
} else {
cg.printObjectHeader("SimpleFunctionCallExpression", 3);
cg.printPropertyHeader("functionExpression");
}
m_nameExp->outputCodeModel(cg);
cg.printPropertyHeader("arguments");
cg.printExpressionVector(m_params);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(m_nameExp->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void DynamicFunctionCall::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
@@ -19,6 +19,7 @@
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/code_model_enums.h"
using namespace HPHP;
@@ -87,6 +88,19 @@ TypePtr DynamicVariable::inferTypes(AnalysisResultPtr ar, TypePtr type,
return m_implementedType = Type::Variant;
}
///////////////////////////////////////////////////////////////////////////////
void DynamicVariable::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("UnaryOpExpression", 3);
cg.printPropertyHeader("expression");
m_exp->outputCodeModel(cg);
cg.printPropertyHeader("operation");
cg.printValue(PHP_DYNAMIC_VARIABLE_OP) ;
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -119,6 +119,19 @@ bool EncapsListExpression::canonCompare(ExpressionPtr e) const {
return m_type == el->m_type;
}
///////////////////////////////////////////////////////////////////////////////
void EncapsListExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("EncapsListExpression", 3);
cg.printPropertyHeader("delimiter");
cg.printValue(m_type);
cg.printPropertyHeader("expressions");
cg.printExpressionVector(m_exps);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
-1
Ver Arquivo
@@ -71,7 +71,6 @@ 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();
}
+20 -2
Ver Arquivo
@@ -17,9 +17,12 @@
#ifndef incl_HPHP_EXPRESSION_H_
#define incl_HPHP_EXPRESSION_H_
#include "hphp/util/deprecated/declare-boost-types.h"
#include "hphp/util/hash-map-typedefs.h"
#include "hphp/compiler/construct.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/util/hash-map-typedefs.h"
#define EXPRESSION_CONSTRUCTOR_BASE_PARAMETERS \
BlockScopePtr scope, LocationPtr loc, Expression::KindOf kindOf
@@ -36,6 +39,7 @@
virtual ExpressionPtr clone(); \
virtual TypePtr inferTypes(AnalysisResultPtr ar, TypePtr type, \
bool coerce); \
virtual void outputCodeModel(CodeGenerator &cg); \
virtual void outputPHP(CodeGenerator &cg, AnalysisResultPtr ar);
#define DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS \
DECLARE_BASE_EXPRESSION_VIRTUAL_FUNCTIONS; \
@@ -47,7 +51,7 @@ namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(Statement);
DECLARE_BOOST_TYPES(Expression);
DECLARE_EXTENDED_BOOST_TYPES(Expression);
class Variant;
#define DECLARE_EXPRESSION_TYPES(x) \
@@ -77,7 +81,17 @@ class Variant;
x(ClosureExpression, None), \
x(YieldExpression, None), \
x(AwaitExpression, None), \
x(UserAttribute, None)
x(UserAttribute, None), \
x(QueryExpression, None), \
x(FromClause, None), \
x(LetClause, None), \
x(WhereClause, None), \
x(SelectClause, None), \
x(IntoClause, None), \
x(JoinClause, None), \
x(GroupClause, None), \
x(OrderbyClause, None), \
x(Ordering, None)
class Expression : public Construct {
public:
@@ -349,6 +363,10 @@ public:
return isNoRemove() && m_assertedType;
}
virtual bool allowCellByRef() const {
return false;
}
static ExpressionPtr MakeConstant(AnalysisResultConstPtr ar,
BlockScopePtr scope,
LocationPtr loc,
+19 -19
Ver Arquivo
@@ -33,7 +33,6 @@ using namespace HPHP;
ExpressionList::ExpressionList(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ListKind kind)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(ExpressionList)),
m_outputCount(-1),
m_arrayElements(false), m_collectionType(0), m_kind(kind) {
}
@@ -240,28 +239,17 @@ void ExpressionList::stripConcat() {
BinaryOpExpressionPtr b
(static_pointer_cast<BinaryOpExpression>(e));
if (b->getOp() == '.') {
e = b->getExp1();
el.insertElement(b->getExp2(), i + 1);
continue;
if(!b->getExp1()->isArray() && !b->getExp2()->isArray()) {
e = b->getExp1();
el.insertElement(b->getExp2(), i + 1);
continue;
}
}
}
i++;
}
}
void ExpressionList::setOutputCount(int count) {
assert(count >= 0 && count <= (int)m_exps.size());
m_outputCount = count;
}
int ExpressionList::getOutputCount() const {
return m_outputCount < 0 ? m_exps.size() : m_outputCount;
}
void ExpressionList::resetOutputCount() {
m_outputCount = -1;
}
void ExpressionList::markParam(int p, bool noRefWrapper) {
ExpressionPtr param = (*this)[p];
if (param->hasContext(Expression::InvokeArgument)) {
@@ -286,7 +274,7 @@ void ExpressionList::markParams(bool noRefWrapper) {
}
}
void ExpressionList::setCollectionType(int cType) {
void ExpressionList::setCollectionType(Collection::Type cType) {
m_arrayElements = true;
m_collectionType = cType;
}
@@ -478,6 +466,19 @@ bool ExpressionList::canonCompare(ExpressionPtr e) const {
m_kind == l->m_kind;
}
///////////////////////////////////////////////////////////////////////////////
void ExpressionList::outputCodeModel(CodeGenerator &cg) {
for (unsigned int i = 0; i < m_exps.size(); i++) {
ExpressionPtr exp = m_exps[i];
if (exp) {
cg.printExpression(exp, exp->hasContext(RefParameter));
} else {
cg.printNull();
}
}
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -513,4 +514,3 @@ unsigned int ExpressionList::checkLitstrKeys() const {
}
return keys.size();
}
+1 -10
Ver Arquivo
@@ -73,15 +73,7 @@ public:
void markParam(int p, bool noRefWrapper);
void markParams(bool noRefWrapper);
void setCollectionType(int cType);
/**
* When a function call has too many arguments, we only want to output
* max number of arguments, by limiting output count of subexpressions.
*/
void setOutputCount(int count);
int getOutputCount() const;
void resetOutputCount();
void setCollectionType(Collection::Type cType);
virtual bool canonCompare(ExpressionPtr e) const;
@@ -97,7 +89,6 @@ private:
unsigned int checkLitstrKeys() const;
ExpressionPtrVec m_exps;
int m_outputCount;
bool m_arrayElements;
int m_collectionType;
ListKind m_kind;
+111
Ver Arquivo
@@ -0,0 +1,111 @@
/*
+----------------------------------------------------------------------+
| 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/group_clause.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
GroupClause::GroupClause
(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr coll, ExpressionPtr key)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(GroupClause)),
m_coll(coll), m_key(key) {
}
ExpressionPtr GroupClause::clone() {
GroupClausePtr exp(new GroupClause(*this));
Expression::deepCopy(exp);
exp->m_coll = Clone(m_coll);
exp->m_key = Clone(m_key);
return exp;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
void GroupClause::analyzeProgram(AnalysisResultPtr ar) {
m_coll->analyzeProgram(ar);
m_key->analyzeProgram(ar);
}
ConstructPtr GroupClause::getNthKid(int n) const {
switch (n) {
case 0:
return m_coll;
case 1:
return m_key;
default:
assert(false);
break;
}
return ConstructPtr();
}
int GroupClause::getKidCount() const {
return 2;
}
void GroupClause::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_coll = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_key = dynamic_pointer_cast<Expression>(cp);
break;
default:
break;
}
}
TypePtr GroupClause::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
m_coll->inferAndCheck(ar, Type::Some, false);
m_key->inferAndCheck(ar, Type::Some, false);
return Type::Object;
}
///////////////////////////////////////////////////////////////////////////////
void GroupClause::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("GroupClause", 3);
cg.printPropertyHeader("collection");
m_coll->outputCodeModel(cg);
cg.printPropertyHeader("key");
m_key->outputCodeModel(cg);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void GroupClause::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
cg_printf("group ");
m_coll->outputPHP(cg, ar);
cg_printf(" by ");
m_key->outputPHP(cg, ar);
}
+45
Ver Arquivo
@@ -0,0 +1,45 @@
/*
+----------------------------------------------------------------------+
| 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_GROUP_CLAUSE_H_
#define incl_HPHP_GROUP_CLAUSE_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/expression_list.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(GroupClause);
class GroupClause : public Expression {
public:
GroupClause(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr coll, ExpressionPtr key);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
ExpressionPtr getColl() { return m_coll; }
ExpressionPtr getKey() { return m_key; }
private:
ExpressionPtr m_coll;
ExpressionPtr m_key;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_GROUP_CLAUSE_H_
@@ -283,6 +283,12 @@ TypePtr IncludeExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return UnaryOpExpression::inferTypes(ar, type, coerce);
}
///////////////////////////////////////////////////////////////////////////////
void IncludeExpression::outputCodeModel(CodeGenerator &cg) {
UnaryOpExpression::outputCodeModel(cg);
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
+138
Ver Arquivo
@@ -0,0 +1,138 @@
/*
+----------------------------------------------------------------------+
| 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/join_clause.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
JoinClause::JoinClause
(EXPRESSION_CONSTRUCTOR_PARAMETERS,
const std::string &var, ExpressionPtr coll, ExpressionPtr left,
ExpressionPtr right, const std::string &group)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(JoinClause)),
m_var(var), m_coll(coll), m_left(left),
m_right(right), m_group(group) {
}
ExpressionPtr JoinClause::clone() {
JoinClausePtr exp(new JoinClause(*this));
Expression::deepCopy(exp);
exp->m_var = m_var;
exp->m_coll = Clone(m_coll);
exp->m_left = Clone(m_left);
exp->m_right = Clone(m_right);
exp->m_group = m_group;
return exp;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
void JoinClause::analyzeProgram(AnalysisResultPtr ar) {
m_coll->analyzeProgram(ar);
m_left->analyzeProgram(ar);
m_right->analyzeProgram(ar);
}
ConstructPtr JoinClause::getNthKid(int n) const {
switch (n) {
case 0:
return m_coll;
case 1:
return m_left;
case 2:
return m_right;
default:
assert(false);
break;
}
return ConstructPtr();
}
int JoinClause::getKidCount() const {
return 3;
}
void JoinClause::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_coll = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_left = dynamic_pointer_cast<Expression>(cp);
break;
case 2:
m_right = dynamic_pointer_cast<Expression>(cp);
break;
default:
break;
}
}
TypePtr JoinClause::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
m_coll->inferAndCheck(ar, Type::Some, false);
m_left->inferAndCheck(ar, Type::Some, false);
m_right->inferAndCheck(ar, Type::Some, false);
return Type::Object;
}
///////////////////////////////////////////////////////////////////////////////
void JoinClause::outputCodeModel(CodeGenerator &cg) {
auto numProps = 5;
if (!m_group.empty()) numProps++;
cg.printObjectHeader("JoinClause", numProps);
cg.printPropertyHeader("variable");
cg.printValue(m_var);
cg.printPropertyHeader("collection");
m_coll->outputCodeModel(cg);
cg.printPropertyHeader("left");
m_left->outputCodeModel(cg);
cg.printPropertyHeader("right");
m_right->outputCodeModel(cg);
if (!m_group.empty()) {
cg.printPropertyHeader("group");
cg.printValue(m_group);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void JoinClause::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
cg_printf("join %s in ", m_var.c_str());
m_coll->outputPHP(cg, ar);
cg_printf(" on ");
m_left->outputPHP(cg, ar);
cg_printf(" equals ");
m_right->outputPHP(cg, ar);
if (!m_group.empty()) {
cg_printf(" into %s", m_group.c_str());
}
}
+52
Ver Arquivo
@@ -0,0 +1,52 @@
/*
+----------------------------------------------------------------------+
| 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_JOIN_CLAUSE_H_
#define incl_HPHP_JOIN_CLAUSE_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/expression_list.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(JoinClause);
class JoinClause : public Expression {
public:
JoinClause(EXPRESSION_CONSTRUCTOR_PARAMETERS,
const std::string &var, ExpressionPtr coll, ExpressionPtr left,
ExpressionPtr right, const std::string &group);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
std::string getVar() const { return m_var; }
ExpressionPtr getColl() { return m_coll; }
ExpressionPtr getLeft() { return m_left; }
ExpressionPtr getRight() { return m_right; }
std::string getGroup() { return m_group; }
private:
std::string m_var;
ExpressionPtr m_coll;
ExpressionPtr m_left;
ExpressionPtr m_right;
std::string m_group;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_JOIN_CLAUSE_H_
+27 -1
Ver Arquivo
@@ -31,7 +31,7 @@ using namespace HPHP;
// constructors/destructors
/*
Determine whether the rhs behaves normall, or abnormally.
Determine whether the rhs behaves normally, or abnormally.
1) If the expression is the silence operator, recurse on the inner expression.
2) If the expression is a list assignment expression, recurse on the
@@ -77,6 +77,7 @@ static ListAssignment::RHSKind GetRHSKind(ExpressionPtr rhs) {
case Expression::KindOfIncludeExpression:
case Expression::KindOfYieldExpression:
case Expression::KindOfAwaitExpression:
case Expression::KindOfQueryExpression:
return ListAssignment::Regular;
case Expression::KindOfListAssignment:
@@ -118,6 +119,15 @@ static ListAssignment::RHSKind GetRHSKind(ExpressionPtr rhs) {
case Expression::KindOfParameterExpression:
case Expression::KindOfModifierExpression:
case Expression::KindOfUserAttribute:
case Expression::KindOfFromClause:
case Expression::KindOfLetClause:
case Expression::KindOfWhereClause:
case Expression::KindOfSelectClause:
case Expression::KindOfIntoClause:
case Expression::KindOfJoinClause:
case Expression::KindOfGroupClause:
case Expression::KindOfOrderbyClause:
case Expression::KindOfOrdering:
always_assert(false);
// non-arrays
@@ -273,6 +283,22 @@ TypePtr ListAssignment::inferTypes(AnalysisResultPtr ar, TypePtr type,
return m_array->inferAndCheck(ar, Type::Variant, false);
}
///////////////////////////////////////////////////////////////////////////////
void ListAssignment::outputCodeModel(CodeGenerator &cg) {
auto numProps = m_array != nullptr ? 3 : 2;
cg.printObjectHeader("ListAssignmentExpression", numProps);
cg.printPropertyHeader("variables");
cg.printExpressionVector(m_variables);
if (m_array != nullptr) {
cg.printPropertyHeader("expression");
m_array->outputCodeModel(cg);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -118,6 +118,20 @@ bool ModifierExpression::validForClosure() const {
return true;
}
/**
* In the context of a trait alias rule, only method access and visibility
* modifiers are allowed
*/
bool ModifierExpression::validForTraitAliasRule() const {
for (auto const& mod: m_modifiers) {
if (mod != T_PUBLIC && mod != T_PRIVATE && mod != T_PROTECTED
&& mod != T_FINAL) {
return false;
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
@@ -131,6 +145,29 @@ TypePtr ModifierExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return TypePtr();
}
///////////////////////////////////////////////////////////////////////////////
void ModifierExpression::outputCodeModel(CodeGenerator &cg) {
cg.printf("V:9:\"HH\\Vector\":%d:{", (int)m_modifiers.size());
for (unsigned int i = 0; i < m_modifiers.size(); i++) {
cg.printObjectHeader("Modifier", 1);
cg.printPropertyHeader("name");
switch (m_modifiers[i]) {
case T_PUBLIC: cg.printValue("public"); break;
case T_PROTECTED: cg.printValue("protected"); break;
case T_PRIVATE: cg.printValue("private"); break;
case T_STATIC: cg.printValue("static"); break;
case T_ABSTRACT: cg.printValue("abstract"); break;
case T_FINAL: cg.printValue("final"); break;
case T_ASYNC: cg.printValue("async"); break;
default:
assert(false);
}
cg.printObjectFooter();
}
cg.printf("}");
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -56,6 +56,7 @@ public:
bool validForFunction() const;
bool validForClosure() const;
bool validForTraitAliasRule() const;
void setHasPrivacy(bool f) { m_hasPrivacy = f; }
@@ -122,7 +122,6 @@ TypePtr NewObjectExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
if (getScope()->isFirstPass()) {
Compiler::Error(Compiler::BadConstructorCall, self);
}
m_params->setOutputCount(0);
}
m_params->inferAndCheck(ar, Type::Some, false);
}
@@ -153,6 +152,25 @@ TypePtr NewObjectExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
return Type::Object;
}
///////////////////////////////////////////////////////////////////////////////
void NewObjectExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("NewObjectExpression", m_params == nullptr ? 2 : 3);
if (m_nameExp->is(Expression::KindOfScalarExpression)) {
cg.printPropertyHeader("className");
} else {
cg.printPropertyHeader("classExpression");
}
m_nameExp->outputCodeModel(cg);
if (m_params != nullptr) {
cg.printPropertyHeader("arguments");
cg.printExpressionVector(m_params);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -146,7 +146,6 @@ void ObjectMethodExpression::setInvokeParams(AnalysisResultPtr ar) {
for (int i = 0; i < m_params->getCount(); i++) {
(*m_params)[i]->inferAndCheck(ar, Type::Variant, false);
}
m_params->resetOutputCount();
}
ExpressionPtr ObjectMethodExpression::preOptimize(AnalysisResultConstPtr ar) {
@@ -278,6 +277,28 @@ TypePtr ObjectMethodExpression::inferAndCheck(AnalysisResultPtr ar,
return checkParamsAndReturn(ar, type, coerce, func, false);
}
///////////////////////////////////////////////////////////////////////////////
void ObjectMethodExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("ObjectMethodCallExpression",
m_params == nullptr ? 3 : 4);
cg.printPropertyHeader("object");
m_object->outputCodeModel(cg);
if (m_nameExp->is(Expression::KindOfScalarExpression)) {
cg.printPropertyHeader("methodName");
} else {
cg.printPropertyHeader("methodExpression");
}
m_nameExp->outputCodeModel(cg);
if (m_params != nullptr) {
cg.printPropertyHeader("arguments");
cg.printExpressionVector(m_params);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
@@ -332,6 +332,23 @@ ObjectPropertyExpression::postOptimize(AnalysisResultConstPtr ar) {
ExpressionPtr();
}
///////////////////////////////////////////////////////////////////////////////
void ObjectPropertyExpression::outputCodeModel(CodeGenerator &cg) {
cg.printObjectHeader("ObjectPropertyExpression", 3);
cg.printPropertyHeader("object");
m_object->outputCodeModel(cg);
if (m_property->is(Expression::KindOfScalarExpression)) {
cg.printPropertyHeader("propertyName");
} else {
cg.printPropertyHeader("propertyExpression");
}
m_property->outputCodeModel(cg);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
+126
Ver Arquivo
@@ -0,0 +1,126 @@
/*
+----------------------------------------------------------------------+
| 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/ordering.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
Ordering::Ordering
(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr key, TokenID direction)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(Ordering)),
m_key(key), m_direction(direction){
}
ExpressionPtr Ordering::clone() {
OrderingPtr exp(new Ordering(*this));
Expression::deepCopy(exp);
exp->m_key = Clone(m_key);
exp->m_direction = m_direction;
return exp;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
void Ordering::analyzeProgram(AnalysisResultPtr ar) {
m_key->analyzeProgram(ar);
}
ConstructPtr Ordering::getNthKid(int n) const {
switch (n) {
case 0:
return m_key;
default:
assert(false);
break;
}
return ConstructPtr();
}
int Ordering::getKidCount() const {
return 1;
}
void Ordering::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_key = dynamic_pointer_cast<Expression>(cp);
break;
default:
break;
}
}
TypePtr Ordering::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
m_key->inferAndCheck(ar, Type::Some, false);
return Type::Object;
}
///////////////////////////////////////////////////////////////////////////////
void Ordering::outputCodeModel(CodeGenerator &cg) {
int direction;
switch (m_direction) {
case T_ASCENDING:
direction = 1;
break;
case T_DESCENDING:
direction = 2;
break;
default:
direction = 3;
break;
}
auto propCount = direction > 0 ? 3 : 2;
cg.printObjectHeader("Ordering", propCount);
cg.printPropertyHeader("key");
m_key->outputCodeModel(cg);
if (propCount == 3) {
cg.printPropertyHeader("direction");
cg.printValue(direction);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void Ordering::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
m_key->outputPHP(cg, ar);
switch (m_direction) {
case T_ASCENDING:
cg_printf(" ascending");
break;
case T_DESCENDING:
cg_printf(" decending");
break;
default:
break;
}
}
+47
Ver Arquivo
@@ -0,0 +1,47 @@
/*
+----------------------------------------------------------------------+
| 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_ORDERING_H_
#define incl_HPHP_ORDERING_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/parser/scanner.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(Ordering);
class Ordering : public Expression {
public:
Ordering(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr key, TokenID direction);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
ExpressionPtr getKey() const { return m_key; }
TokenID getDirection() { return m_direction; }
private:
ExpressionPtr m_key;
TokenID m_direction;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_ORDERING_H_
@@ -300,6 +300,45 @@ void ParameterExpression::compatibleDefault() {
}
}
///////////////////////////////////////////////////////////////////////////////
void ParameterExpression::outputCodeModel(CodeGenerator &cg) {
auto propCount = 2;
if (m_attributeList) propCount++;
if (m_modifier != 0) propCount++;
if (m_ref) propCount++;
if (m_defaultValue != nullptr) propCount++;
cg.printObjectHeader("ParameterDeclaration", propCount);
if (m_attributeList) {
cg.printPropertyHeader("isPassedByReference");
cg.printExpressionVector(m_attributeList);
}
if (m_modifier != 0) {
cg.printPropertyHeader("modifiers");
printf("V:9:\"HH\\Vector\":1:{");
switch (m_modifier) {
case T_PUBLIC: cg.printValue("public"); break;
case T_PROTECTED: cg.printValue("protected"); break;
case T_PRIVATE: cg.printValue("private"); break;
default: assert(false);
}
printf("}");
}
if (m_ref) {
cg.printPropertyHeader("isPassedByReference");
cg.printValue(true);
}
cg.printPropertyHeader("name");
cg.printValue(m_name);
if (m_defaultValue) {
cg.printPropertyHeader("expression");
m_defaultValue->outputCodeModel(cg);
}
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
+1 -1
Ver Arquivo
@@ -19,7 +19,7 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/util/json.h"
#include "hphp/compiler/json.h"
#include "hphp/parser/scanner.h"
namespace HPHP {
+22
Ver Arquivo
@@ -163,6 +163,28 @@ ExpressionPtr QOpExpression::unneededHelper() {
return static_pointer_cast<Expression>(shared_from_this());
}
///////////////////////////////////////////////////////////////////////////////
void QOpExpression::outputCodeModel(CodeGenerator &cg) {
if (m_expYes == nullptr) {
cg.printObjectHeader("ValueIfNullExpression", 3);
cg.printPropertyHeader("expression");
m_condition->outputCodeModel(cg);
cg.printPropertyHeader("valueIfNull");
} else {
cg.printObjectHeader("ConditionalExpression", 4);
cg.printPropertyHeader("condition");
m_condition->outputCodeModel(cg);
cg.printPropertyHeader("valueIfTrue");
m_expYes->outputCodeModel(cg);
cg.printPropertyHeader("valueIfFalse");
}
m_expNo->outputCodeModel(cg);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
+165
Ver Arquivo
@@ -0,0 +1,165 @@
/*
+----------------------------------------------------------------------+
| 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/query_expression.h"
#include "hphp/compiler/expression/simple_query_clause.h"
#include "hphp/compiler/analysis/capture_extractor.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
QueryOrderby::QueryOrderby(EXPRESSION_CONSTRUCTOR_BASE_PARAMETERS)
: Expression(EXPRESSION_CONSTRUCTOR_BASE_PARAMETER_VALUES) {
m_expressions = nullptr;
}
ExpressionPtr QueryOrderby::clone() {
assert(false);
return nullptr;
}
QueryExpression::QueryExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr head, ExpressionPtr body)
: QueryOrderby(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(QueryExpression)) {
m_queryargs = ExpressionListPtr(
new ExpressionList(getScope(), getLocation())
);
m_expressions = ExpressionListPtr(
new ExpressionList(getScope(), getLocation())
);
m_expressions->addElement(head);
assert(body != nullptr && body->is(Expression::KindOfExpressionList));
ExpressionListPtr el(static_pointer_cast<ExpressionList>(body));
for (unsigned int i = 0; i < el->getCount(); i++) {
if ((*el)[i]) m_expressions->addElement((*el)[i]);
}
}
QueryExpression::QueryExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionListPtr clauses)
: QueryOrderby(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(QueryExpression)) {
m_queryargs = ExpressionListPtr(
new ExpressionList(getScope(), getLocation())
);
m_expressions = clauses;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
ExpressionListPtr QueryExpression::getQueryArguments() {
if (m_queryargs->getCount() == 0) serializeQueryExpression();
return m_queryargs;
}
StringData* QueryExpression::getQueryString() {
if (m_querystr == nullptr) serializeQueryExpression();
return m_querystr;
}
void QueryExpression::serializeQueryExpression() {
CaptureExtractor ce;
auto qe = ce.rewrite(static_pointer_cast<Expression>(shared_from_this()));
m_queryargs->clearElements();
for (auto e : ce.getCapturedExpressions()) {
m_queryargs->addElement(e);
}
assert(m_queryargs->getCount() > 0); //syntax requires an initial from clause
std::ostringstream serialized;
CodeGenerator cg(&serialized, CodeGenerator::Output::CodeModel);
cg.setAstClassPrefix("Code"); //TODO: create option for this
qe->outputCodeModel(cg);
std::string s(serialized.str().c_str(), serialized.str().length());
m_querystr = makeStaticString(s);
}
void QueryOrderby::analyzeProgram(AnalysisResultPtr ar) {
for (unsigned int i = 0; i < m_expressions->getCount(); i++) {
(*m_expressions)[i]->analyzeProgram(ar);
}
}
ConstructPtr QueryOrderby::getNthKid(int n) const {
if (n < (int)m_expressions->getCount()) {
return (*m_expressions)[n];
}
return ConstructPtr();
}
int QueryOrderby::getKidCount() const {
return m_expressions->getCount();
}
void QueryOrderby::setNthKid(int n, ConstructPtr cp) {
int m = m_expressions->getCount();
if (n >= m) {
assert(false);
} else {
(*m_expressions)[n] = dynamic_pointer_cast<Expression>(cp);
}
}
TypePtr QueryOrderby::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
for (unsigned int i = 0; i < m_expressions->getCount(); i++) {
if (ExpressionPtr e = (*m_expressions)[i]) {
e->inferAndCheck(ar, Type::Some, false);
}
}
return Type::Object;
}
///////////////////////////////////////////////////////////////////////////////
void QueryOrderby::outputCodeModel(CodeGenerator &cg) {
if (this->getKindOf() == Expression::KindOfOrderbyClause) {
cg.printObjectHeader("OrderbyClause", 2);
} else {
cg.printObjectHeader("QueryExpression", 2);
}
cg.printPropertyHeader("clauses");
m_expressions->outputCodeModel(cg);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
// code generation functions
void QueryOrderby::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
if (this->getKindOf() == Expression::KindOfOrderbyClause) {
cg_printf("orderby ");
}
for (unsigned int i = 0; i < m_expressions->getCount(); i++) {
if (ExpressionPtr e = (*m_expressions)[i]) {
e->outputPHP(cg, ar);
if (i > 0) cg_printf(" ");
}
}
}
+89
Ver Arquivo
@@ -0,0 +1,89 @@
/*
+----------------------------------------------------------------------+
| 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_QUERY_EXPRESSION_H_
#define incl_HPHP_QUERY_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/runtime/base/static-string-table.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(QueryOrderby);
class QueryOrderby : public Expression {
public:
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
protected:
explicit QueryOrderby(EXPRESSION_CONSTRUCTOR_BASE_PARAMETERS);
ExpressionListPtr m_expressions;
};
DECLARE_BOOST_TYPES(QueryExpression);
class QueryExpression : public QueryOrderby {
public:
QueryExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr head, ExpressionPtr body);
QueryExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionListPtr clauses);
virtual ExpressionPtr clone() {
QueryExpressionPtr exp(new QueryExpression(*this));
Expression::deepCopy(exp);
exp->m_expressions = Clone(m_expressions);
exp->m_queryargs = Clone(m_queryargs);
exp->m_querystr = m_querystr;
return exp;
}
ExpressionListPtr getClauses() const { return m_expressions; }
ExpressionListPtr getQueryArguments();
StringData* getQueryString();
private:
void serializeQueryExpression();
ExpressionListPtr m_queryargs;
StringData* m_querystr;
};
DECLARE_BOOST_TYPES(OrderbyClause);
class OrderbyClause : public QueryOrderby {
public:
OrderbyClause(EXPRESSION_CONSTRUCTOR_PARAMETERS, ExpressionPtr orderings)
: QueryOrderby(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(OrderbyClause)) {
assert(orderings && orderings->is(Expression::KindOfExpressionList));
m_expressions = static_pointer_cast<ExpressionList>(orderings);
}
virtual ExpressionPtr clone() {
OrderbyClausePtr exp(new OrderbyClause(*this));
Expression::deepCopy(exp);
exp->m_expressions = Clone(m_expressions);
return exp;
}
ExpressionListPtr getOrderings() const { return m_expressions; }
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_QUERY_EXPRESSION_H_
+53 -2
Ver Arquivo
@@ -384,6 +384,48 @@ std::string ScalarExpression::getIdentifier() const {
return "";
}
///////////////////////////////////////////////////////////////////////////////
void ScalarExpression::outputCodeModel(CodeGenerator &cg) {
switch (m_type) {
case T_NS_C:
case T_LINE:
case T_TRAIT_C:
case T_CLASS_C:
case T_METHOD_C:
case T_FUNC_C: {
cg.printObjectHeader("SimpleVariableExpression", 2);
std::string varName;
switch (m_type) {
case T_NS_C: varName = "__NAMESPACE__"; break;
case T_LINE: varName = "__LINE__"; break;
case T_TRAIT_C: varName = "__TRAIT__"; break;
case T_CLASS_C: varName = "__CLASS__"; break;
case T_METHOD_C: varName = "__METHOD__"; break;
case T_FUNC_C: varName = "__FUNCTION__"; break;
default: break;
}
cg.printPropertyHeader("variableName");
cg.printValue(varName);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
return;
}
default:
break;
}
cg.printObjectHeader("ScalarExpression", 2);
cg.printPropertyHeader("value");
cg.printValue(m_originalValue);
cg.printPropertyHeader("sourceLocation");
cg.printLocation(this->getLocation());
cg.printObjectFooter();
}
///////////////////////////////////////////////////////////////////////////////
void ScalarExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
switch (m_type) {
case T_CONSTANT_ENCAPSED_STRING:
@@ -459,7 +501,7 @@ Variant ScalarExpression::getVariant() const {
return String(m_value);
case T_LNUMBER:
case T_COMPILER_HALT_OFFSET:
return strtoll(m_value.c_str(), nullptr, 0);
return getIntValue();
case T_LINE:
return String(m_translated).toInt64();
case T_TRAIT_C:
@@ -498,7 +540,7 @@ bool ScalarExpression::getString(const std::string *&s) const {
bool ScalarExpression::getInt(int64_t &i) const {
if (m_type == T_LNUMBER || m_type == T_COMPILER_HALT_OFFSET) {
i = strtoll(m_value.c_str(), nullptr, 0);
i = getIntValue();
return true;
} else if (m_type == T_LINE) {
i = getLocation() ? getLocation()->line1 : 0;
@@ -524,3 +566,12 @@ void ScalarExpression::setCompilerHaltOffset(int64_t ofs) {
m_value = ss.str();
m_originalValue = ss.str();
}
int64_t ScalarExpression::getIntValue() const {
// binary number syntax "0b" is not supported by strtoll
if (m_value.compare(0, 2, "0b") == 0) {
return strtoll(m_value.c_str() + 2, nullptr, 2);
}
return strtoll(m_value.c_str(), nullptr, 0);
}
@@ -87,6 +87,8 @@ private:
std::string m_translated;
bool m_quoted;
std::string m_comment; // for inlined constant name
int64_t getIntValue() const;
};
///////////////////////////////////////////////////////////////////////////////

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais