2473 Commits

Autor SHA1 Mensagem Data
Paul Tarjan c4499f273d parallel makes 2014-01-28 19:50:23 -08:00
Erik b538a34e89 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 15:38:35 -08:00
Sean Cannella c3b11e0c55 Switch Map and Set to use tracked smart allocators
Switches Map and Set to use tracked allocators. Vector uses
smart_realloc which will require a bit more work.

Reviewed By: @edwinsmith

Differential Revision: D1146939
2014-01-28 15:38:31 -08:00
Paul Tarjan 62c0212045 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-28 15:38:28 -08:00
Daniel Sloof b4845ed26d SimpleXML rewrite
Update SimpleXML to be compliant with Zend and fix a bunch of
tests.

Closes #1387
Closes #1530

Reviewed By: @ptarjan

Differential Revision: D1135882

Pulled By: @scannell
2014-01-28 15:38:21 -08:00
rbelenov fe7a4fcff9 Support for Intel VTune Amplifier XE
Intel VTune Amplifier XE
(http://software.intel.com/en-us/intel-vtune-amplifier-xe), the
performance analysis tool, supports mapping of performance data from IP
addresses to function names and source file/lines for custom JIT
engines; the engine should provide mapping from generated code to source
using JIT API (http://software.intel.com/en-us/node/458070). This patch
add the reporting to hhvm, allowing to profile PHP code execution and
see both generated assembly and PHP source for hotspots.

The reporting is controlled via Eval.JitUseVtuneAPI runtime option, so
the default behaviour is not affected. If the option is set and hhvm is
profiled by VTune, the information on compiled code is reported via JIT
API and stored in data file which is used during postprocessing and data
visualization.

The patch includes some files from VTune; the are distrubuted under BSD
license.

Closes #1254

Reviewed By: @ottoni

Differential Revision: D1133559

Pulled By: @scannell
2014-01-28 15:38:17 -08:00
bsimmers fd6d3c4dd2 Disable flaky zend test
Reviewed By: @edwinsmith

Differential Revision: D1147082
2014-01-28 15:38:11 -08:00
Owen Yamauchi d004ca9c6b Implement codegen for Call
After LdLoc went down, this is the next top punt. This forced me to get
the bind-call machinery working, and a bunch of other stuff -- it kind
of snowballed on me. Redispatching from prologues and handling stack
overflow also had to work. We were also forgetting to rewind the
globalData frontier if translation failed, and this change combined with
that to actually blow out globalData in a couple of tests.

Small bonus: deleting a bunch of "JIT::" that used to be "Transl::".

Reviewed By: @edwinsmith

Differential Revision: D1134414
2014-01-28 15:38:07 -08:00
Edwin Smith 35ca2405fc Remove dead function: emitContVarEnvHelperCall().
It was never called.

Reviewed By: @ottoni

Differential Revision: D1146574
2014-01-28 15:38:00 -08:00
Stuart Loxton 8f05139460 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 15:37:53 -08:00
Camillus Gerard Cai 9b2b28d678 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 15:37:49 -08:00
Paul Saab fc26e82dc2 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 15:37:46 -08:00
Fred Emmott e38a481061 Fix scoping for evaling default ReflectionParameter values
Closes #1449
Closes #1652

Reviewed By: @ptarjan

Differential Revision: D1141045
2014-01-28 15:37:42 -08:00
Fred Emmott 379a930d49 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 15:37:39 -08:00
Fred Emmott f2f8c75444 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 15:37:35 -08:00
Fred Emmott c68c15b39f 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 15:37:32 -08:00
Sara Golemon d776975c82 Revert "Build ext_zend_compat extensions by default"
This reverts commit 8bf8e13796.

Not behaving as it's supposed to.  Revert until I can figure that out.
2014-01-28 11:11:46 -08:00
Sara Golemon 8bf8e13796 Build ext_zend_compat extensions by default 2014-01-28 09:17:56 -08:00
Jim Radford c052283289 Implement stream_context_{get,set}_default
Implement stream_context_{get,set}_default

Closes #1642

Reviewed By: @ptarjan

Differential Revision: D1145658

Pulled By: @scannell
2014-01-28 09:17:56 -08:00
Sean Cannella a9c43f1b82 Convert ext/zlib to HNI
Convert ext/zlib to HNI

Closes #1635

Reviewed By: @ptarjan

Differential Revision: D1143714
2014-01-28 09:17:55 -08:00
Jim Radford 7d4b75583e 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 09:17:55 -08:00
Jim Radford 05c1c762f4 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 09:17:54 -08:00
Drew Paroski 09d121c851 Update array_shift to support collections
This diff updates the implementation of array_shift to support mutable
collections. A very simple scheme was used to make Vector and Set support
adding elements to the front similar to what HphpArray currently does. I
leave improving the data structures' perf when adding elements to the front
to a subsequent diff.

Reviewed By: @elgenie

Differential Revision: D1140008
2014-01-28 09:17:54 -08:00
Eugene Letuchy 1f3095e8cc make phinq tests slightly more reviewable
... attempting to use diff on expect files containing
 non-printing characters doesn't seem like a good idea, and having
 .expect that are treated as binary makes them hard to review.

Reviewed By: @hermanventer

Differential Revision: D1144149

(flaky www test)
2014-01-28 09:17:54 -08:00
Paul Tarjan b69b36096d 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 09:17:53 -08:00
Edwin Smith a55228796d Fix XLS spill slot alignment for SIMD registers
If XLS spills a SIMD register, we need the spill slot to
be 16-byte aligned. Also the checkShuffle() assertions weren't
quite right when spilling/loading SIMD registers.

Reviewed By: @jdelong

Differential Revision: D1144168
2014-01-28 09:17:53 -08:00
Owen Yamauchi 9070858a18 Implement codegen for SpillFrame, CallBuiltin, CheckType
SpillFrame is the next top punt after Call. This diff is preparation to
get the Call diff to pass all the tests. Also:

- I removed some code that I said I was going to remove in my last diff
  but forgot. :/

- There was a bug in emitStore, where I was failing to zero-extend bool
  srcs. This caused some interesting test failures once CallBuiltin was
  implemented, because if you call a builtin that returns bool from C++,
  you'll get garbage in the higher-order bytes.

- I had to increase the max number of arguments you can pass to a host
  call.

- Finally, I moved the reserved-stack-space constants out of the X64
  namespace and strengthened some of the asserts around the simulator's
  stack pointer (I ran into this while working).

Reviewed By: @edwinsmith

Differential Revision: D1139057
2014-01-28 09:17:52 -08:00
Paul Tarjan f7d82dfa0b document --php
Closes #1610

Reviewed By: @jdelong

Differential Revision: D1145021
2014-01-28 09:17:52 -08:00
Edwin Smith 9582398cb9 Remove legacy linear scan register allocator
Also rename linear-scan.h to reg-alloc.h, it still contains
a few leftover definitions and it's a useful place to put
declarations that don't depend on the implementation.

Reviewed By: @swtaarrs

Differential Revision: D1135081
2014-01-28 09:17:52 -08:00
Drew Paroski 3fe57c93db Update array_unshift to support Vector and Set
This diff updates the implementation of array_unshift to support Vector
and Set for the first parameter. A very simple scheme was used to make
Vector and Set support adding elements to the front similar to what
HphpArray currently does. I leave improving the data structures' perf
when adding elements to the front to a subsequent diff.

Along the way, I fixed the behavior of array_unshift() to match PHP 5.5
in the case where the first parameter is not an array, Vector, or Set.

Reviewed By: @elgenie

Differential Revision: D1139932
2014-01-28 09:17:51 -08:00
Jordan DeLong a8956cf943 Fix a bug with properties initialized to __DIR__ or __FILE__
Reported on freenode by nelt.  The deepInitHelper code
assumes the result of any deep-initialized property is reference
counted.  Since we recently changed opcodes that push static strings
to push KindOfStaticString, this means in the interpreter we'd hit an
assertion here.  (The JIT was unaffected, and neither case does
anything wrong in an opt build.)

Reviewed By: @paroski

Differential Revision: D1144110
2014-01-28 09:17:51 -08:00
Paul Tarjan f30fc478c3 try these again
I want to see what contbuild has to say about them

Reviewed By: @scannell

Differential Revision: D1116576
2014-01-28 09:17:50 -08:00
aravind a2df4d2e35 Revert "[hh] autoload: don't swallow fatals when autoloading"
This reverts commit 78e4c601db4c0b6ce55b44ae201fedaf47b65501.

Reviewed By: @elgenie

Differential Revision: D1144365
2014-01-28 09:17:50 -08:00
Eugene Letuchy f58e20caf3 array_slice(): support for collections, remove dead code
A straight-forward delegation to ArrayIter does the job.
 After analysis of the uses of slicing code, it seems that slicing can
 be confined to just the ext_array function, since the other uses for
 func_get_args have been subsumed by special purpose bytecodes. Thus,
 this diff also removes Array::slice, ArrayUtil::Slice, func_get_arg,
 and func_get_args.

Reviewed By: @jdelong

Differential Revision: D1142189
2014-01-28 09:17:50 -08:00
Eugene Letuchy 7613e239a6 collections: get rid of CollectionType::StableMap
... since StableMap is an alias for Map (as of {D1116834}),
 there can be no collections of this type.

Reviewed By: @jdelong

Differential Revision: D1119658
2014-01-28 09:17:49 -08:00
Eugene Letuchy ecc2f9b686 collections: unify StableMap and Map as HH\Map
* Turns ##c_StableMap## into a typedef for ##c_Map##
* ## StableMap ## and ## Map ## are both parse-time aliases for ## HH\Map ## (auto-imported under HipHopSyntax)
* Incorporates anietoro's {D1105491}.

Note: this cannot be committed until we're sure about the equality
semantics that make the most sense for the Map/StableMap hybrid (see {D1116829})

Reviewed By: @paroski

Differential Revision: D1116834
2014-01-28 09:17:49 -08:00
Eugene Letuchy 1903ce4d06 make f_array_rand faster when only one key is to be returned
Same big-O complexity, but smaller constant factors ... iterate
 ~1/2 as many elements, generate 1 instead of n random numbers.

Reviewed By: @jdelong

Differential Revision: D1142089
2014-01-28 09:17:48 -08:00
Eugene Letuchy b90ad1e32d collections: support in array_flip() builtin
A straight-forward iteration does the job.

Reviewed By: @jdelong

Differential Revision: D1142068
2014-01-28 09:17:48 -08:00
Bert Maher 2fbfba627e Avoid assertion failure while trying to print an empty block
Doing block->next() on an empty block causes an assertion
failure.  While that should never happen in normal operation, it's
kind of annoying when you're in gdb and want to print a block without
checking first whether it's empty.

Reviewed By: @ottoni

Differential Revision: D1143080
2014-01-28 09:17:48 -08:00
Eugene Letuchy 11e808ef24 collections: support in array_reverse() builtin
Rather than building a way of iterating every collection in
 reverse, `array_reverse` is accomplished by reversing the result of
 converting the collection to an array.

Reviewed By: @paroski

Differential Revision: D1142062
2014-01-28 09:17:47 -08:00
Paul Tarjan b873e69600 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
2014-01-28 09:17:47 -08:00
bsimmers 20f3e66d92 Disable/trim flaky tests
- Disable sleep_await.php and curlUpload.php for being flaky
- Remove potentially flaky parts from ext_network.php

Reviewed By: @bertmaher

Differential Revision: D1143085
2014-01-28 09:17:46 -08:00
Owen Yamauchi 3ef0ec891d Convert a few CALL_OPCODEs for ARM
These were all causing me trouble with my upcoming diffs -- punting on
these was causing some tests to time out due to punting so much.

Reviewed By: @edwinsmith

Differential Revision: D1142730
2014-01-28 09:17:46 -08:00
Owen Yamauchi a5261ea56c 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 09:17:46 -08:00
Simon Welsh beb5d544a5 Convert standard/url to HNI
Convert standard/url to HNI

Closes #1604

Reviewed By: @ptarjan

Differential Revision: D1135473

Pulled By: @scannell
2014-01-28 09:17:45 -08:00
Eugene Letuchy c724f89d7b autoloading: change currently-loading array to be indexed by classNames
Mainly interested in the perflab here, as looping over all the values
 is certainly less efficient O(autoload-depth) as opposed to O(1).

 Also, gets rid of the last use of Array::valueExists

Reviewed By: @scannell

Differential Revision: D1137619
2014-01-28 09:17:45 -08:00
Fred Emmott 417328fefb Implement ini_get_all()
Used by PHPUnit, as triggered by Mockery

Reviewed By: @ptarjan

Differential Revision: D1136971
2014-01-28 09:17:44 -08:00
Fred Emmott 02694e94e4 Move magic ini settings out of IniSettings
Pre-req on implementing ini_get_all() sanely.

Reviewed By: @ptarjan

Differential Revision: D1134579
2014-01-28 09:17:44 -08:00
Alan Frindell edcdac373b Wait for the PProfServer before main exits
Looking into shutdown crashes I found this one with jemalloc junk enabled.

Reviewed By: @scannell

Differential Revision: D1139409
2014-01-28 09:17:44 -08:00
Edwin Smith 4404f655c5 Reduce default MaxRegs setting to avoid wraparound.
Fix wraparound bug in XLS that was reducing available registers.

Reviewed By: @bertmaher

Differential Revision: D1142120
2014-01-28 09:17:43 -08:00
Guilherme Ottoni 67e3047271 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 09:17:43 -08:00
Bert Maher cdbc15f571 Remove an unused enum from TraceBuilder
It's unused

Reviewed By: @jdelong

Differential Revision: D1140914
2014-01-28 09:17:43 -08:00
bsimmers 41ec39a6ca Hide new assert behind a flag
DbgAssertRetAddr was useful when I was debugging a specific issue but
I think it's a bit excessive for general use. Don't emit it unless we ask for
extra asserts.

Reviewed By: @bertmaher

Differential Revision: D1140555
2014-01-28 09:17:42 -08:00
Jordan DeLong 1ce2c9cae3 Add simplifier case for BoxPtr
Reviewed By: @bertmaher

Differential Revision: D1136598
2014-01-28 09:17:42 -08:00
Jordan DeLong e4a04562a6 Remove partial non-working and not-enabled implementation of IncDecS
There's no case in ir-translator to get here, so this is dead
code.  It looks like it was maybe trying to use a LdMem as a guard, so
I'm not going to try to turn this on---we can implement it later.

Reviewed By: @bertmaher

Differential Revision: D1136590
2014-01-28 09:17:42 -08:00
Jordan DeLong 9fa3ca15f3 When using HNI return types in hhbbc type inference, include TInitNull
I didn't realize but of course they are generally
implied-nullable right now.  (I think we'll eventually want a way to
plumb the nullability through and require things like ?array if it can
be null.)  cc @Alite404Exception

Reviewed By: @dariorussi

Differential Revision: D1135647
2014-01-28 09:17:41 -08:00
Jordan DeLong dc8d03593b Fix a bug in constant propagation
I think this hasn't shown up yet because nothing has been
getting constprop'd with two inputs of different eval stack flavors.

Reviewed By: @dariorussi

Differential Revision: D1135575
2014-01-28 09:17:41 -08:00
Jordan DeLong 619e177992 Improve couldBeThisObj/mustBeThisObj for hhbbc minstr inference
A TODO was to look a the type of bases that aren't inside the
frame.  I did this, but then I realized neither of these changes can
kick in yet.  The couldBeThisObj needs support for unrelated object
types knowing they aren't related (#3343798), and the mustBeThisObj
will always say false if the base isn't in the FrameThis anyway,
because anything we know about a heap type must include InitNull at
least right now.

We might as well put this in as a test case for #3343798 though.  (And
I clarified some comments about how refs work, and fixed something
wrong with BaseR wrt this.)

Reviewed By: @dariorussi

Differential Revision: D1135320
2014-01-28 09:17:40 -08:00
Jordan DeLong abc1e26ee5 Make the JIT actually take advantage of hhbbc private property inference
The JIT wasn't really able to use the private property
information from HHBBC, because by the time we saw an AssertT opcode
the property was already extracted.

This diff changes the hphpcType in each class' property info to a new
RepoAuthType struct which can contain both the kind of information
hhbbc can provide as well as what hphpc can provide.  Sets the JIT up
to use it, and update prediction-opts to handle the hhbbc case (which
will now generate things like LdMem<Obj<Foo>|InitNull> instead of
LdMem<Cell>.)

A later diff will use the same RepoAuthType flag (plus the repo global
data) to fix the issue with unserialize() being able to break inferred
private property types.

Reviewed By: @ottoni

Differential Revision: D1135298
2014-01-28 09:17:40 -08:00
Jordan DeLong 8920673580 Enable private property inference
After D1132987 it seems to work.

Reviewed By: @dariorussi

Differential Revision: D1133202
2014-01-28 09:17:39 -08:00
Bert Maher 802dab3974 Move runtime helper from translator-x64 to translator-runtime
Some random cleanup I came across.

Reviewed By: @swtaarrs

Differential Revision: D1140317
2014-01-28 09:17:39 -08:00
Brandon Wamboldt b1090c3e04 Fix cURL tests by implementing server script
Many cURL extension tests require an HTTP server to be running
with a specific PHP file available.

Travis will now run this script using the built-in HHVM web server.

I've add skip files so if the user doesn't have the required environment
variable set it will skip the tests, just like PHP does.

Closes #1487

Reviewed By: @ptarjan

Differential Revision: D1117179

Pulled By: @scannell
2014-01-28 09:17:39 -08:00
Sean Cannella b54dff5b10 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 09:17:38 -08:00
Ainsley Escorce-Jones 9d28061e71 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 09:17:38 -08:00
Sean Cannella 621b302b23 Revert "Implement ::class"
Reviewed By: ptarjan

This reverts commit 73975187358058e071bbfca5094bb0fc6e23ef86.
2014-01-28 09:17:37 -08:00
Paul Tarjan a94f25001c 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 09:17:37 -08:00
Paul Tarjan eb2312a5de 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 09:17:36 -08:00
Dario Russi 82906a26f5 remove runtime options for APC stats
Now that we removed the options from the config files we can remove the options in the code as well

Reviewed By: @jdelong

Differential Revision: D1135707
2014-01-28 08:05:54 -08:00
Eugene Letuchy 35971e45fa collections: support in_array() and array_search() builtins
... and remove utility functions rendered irrelevant

Reviewed By: @paroski

Differential Revision: D1137616
2014-01-28 08:05:53 -08:00
Alex Malyshev 39bc81c7b0 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 08:05:53 -08:00
Emil Hesslow e77fc64dc7 Break out stuff to mysql_common so I can reuse it for mysqli
- This mostly just moves stuff around. The idea was to put everything that is f_mysql_ in ext_mysql and move everything else into mysql_common
- It also breaks up the query function into two parts because I need it for mysqli
  - Doing the query
  - And getting the result part

Reviewed By: @ptarjan

Differential Revision: D1106027
2014-01-28 08:05:53 -08:00
Fred Emmott c6c2fa766e Add assert to check for Array return types in IDL
'Array' ends up being KindOfObject, and leads to mysterious segfaults.

Reviewed By: @ptarjan

Differential Revision: D1136568
2014-01-28 08:05:52 -08:00
Owen Yamauchi 75e8e34ba7 Implement codegen for StLoc, Box, and CheckStk in ARM
There's one test case that's giving me fits in trying to implement Call,
and if we were just codegen'ing these opcodes, the problem would just go
away. So here they are.

StLoc happens to be third most frequent punt. CheckStk forced me to get
the jump-chaining machinery working, and it's surprisingly simple.

Reviewed By: @ottoni

Differential Revision: D1136517
2014-01-28 08:05:52 -08:00
aravind 4fda422743 Update NEWS for "Coolio"
Per title.

Reviewed By: @ptarjan

Differential Revision: D1136689
2014-01-28 08:05:51 -08:00
Arnaud GRANAL e03fc4652e 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 08:05:51 -08:00
Edwin Smith c5aa39b100 Convert Interval::children to intrusive singly linked list.
std::list is inconvenient for three reasons:
1. when splitting, we have to iterate to find the split position
even though we already have the interval we care about.
2. Loops that visit each split interval must do work for the
parent, then a separate loop for the child.
3. we never need the "prev" pointers

A plain 'next' pointer (aka intrusive singly-linked list) solves
all three problems.

Reviewed By: @bertmaher

Differential Revision: D1135956
2014-01-28 08:05:51 -08:00
Eugene Letuchy 4cc71b677f collections: support min() and max() builtins
Specifically, their one-argument form.

Reviewed By: @paroski

Differential Revision: D1137651
2014-01-28 08:05:50 -08:00
Eugene Letuchy c754019212 collections: support array_fill_keys ...
... and eliminate some single-use array util functions (of
 questionable utility)

Reviewed By: @paroski

Differential Revision: D1137568
2014-01-28 08:05:50 -08:00
Simon Welsh 6c214555e9 Convert ext/apache to HNI
Convert ext/apache to HNI

Closes #1607

Reviewed By: @ptarjan

Differential Revision: D1135889

Pulled By: @scannell
2014-01-28 08:05:45 -08:00
Simon Welsh 6076b94d6d Convert ext/ctype to HNI
Convert ext/ctype to HNI

Closes #1612

Reviewed By: @ptarjan

Differential Revision: D1135975

Pulled By: @scannell
2014-01-28 08:05:01 -08:00
Owen Yamauchi 40100fff5c Normalize ARM's link-register-saving convention
In trying to implement codegen for the Call opcode, I'm running into
problems with the differences between ARM and x64's calling conventions,
specifically with regard to how they save return addresses.

Until now, our ARM code hasn't been treating the link register (the
return address register) like it's supposed to be treated. The register
is technically caller-saved, but normal ARM programs (such as C programs
compiled by gcc) don't save and restore it around callsites. Instead,
non-leaf functions just save it at the very beginning and restore it
just before returning, simply as part of setting up and tearing down the
frame.

What this means for us is that we're now saving it on the stack
immediately on entry to the TC, since, viewed through the traditional
calling-convention lens, the entire TC is a non-leaf function. This
means that we no longer need to save/restore around host calls.

Reviewed By: @edwinsmith

Differential Revision: D1133438
2014-01-28 07:49:27 -08:00
seanc 1e23dec9f0 Split Travis slow/zend test runs further
Summary: This splits the larger Travis test runs roughly evenly to
increase the chance that the tests will pass before hitting the timeout.

Reviewed By: ptarjan
2014-01-22 13:53:44 -08:00
Drew Paroski c1d4b02110 Fix BaseMap::eraseNoCompact to decref string keys
Reviewed By: @elgenie

Differential Revision: D1137646
2014-01-22 12:47:54 -08:00
Bert Maher 9241f43016 Eliminate unused stubBlock() template function
It's unused.

Reviewed By: @swtaarrs

Differential Revision: D1136316
2014-01-22 12:47:54 -08:00
Dario Russi ed23d1a406 Normalize string wrt namespace when used in function or class context
Bytecodes that resolve strings to a class or a function need to normalize the string so it never starts with '\'

Reviewed By: @jdelong

Differential Revision: D1135085
2014-01-22 12:47:54 -08:00
Bert Maher f041b97bff Remove MethodLookup namespace
Namespace isn't needed now that we're using enum classes.

Reviewed By: @jdelong

Differential Revision: D1135968
2014-01-22 12:47:54 -08:00
Jordan DeLong 3009a5a45d Resize the static string table after argument parsing if the size was wrong
Also, change the default size to match cli.hdf, so we don't
do a resize on command line scripts.

Reviewed By: @edwinsmith

Differential Revision: D1126293
2014-01-22 12:47:54 -08:00
Jordan DeLong 2440764f5e Remove MetaInfo::Kind::NonRefCounted
This has been disabled since shortly after it was added,
since hphpc doesn't handle exception edges correctly and reports wrong
information.

Reviewed By: @swtaarrs

Differential Revision: D1135310
2014-01-22 12:47:53 -08:00
Jordan DeLong 13364a8234 Remove AssertStkVal/OverrideLocVal and HHBCTranslator::assertString
Dead after D1133071.  bsimmers said he never really liked
them anyway.

Reviewed By: @swtaarrs

Differential Revision: D1135305
2014-01-22 12:47:53 -08:00
Jordan DeLong 4d9f5d33ef Remove MetaInfo::Kind::String; seems to not kick in anymore
Quite a while back I perflabbed turning this off and saw red,
but I think it must've been noise.  I ran perflabs with an
always_assert(0) in applyInputMetaData here and it never triggered.

Reviewed By: @edwinsmith

Differential Revision: D1133071
2014-01-22 12:47:53 -08:00
Jordan DeLong 994c02283b Use raise_typehint_error for ?Foo hints
So we can use them in static analysis.  Requires a www change
for the error handler.

Reviewed By: @elgenie

Differential Revision: D1125242
2014-01-22 12:47:53 -08:00
Nicholas Ormrod 15de092f49 Removed duplicate #includes
Removed duplicate #includes.

Reviewed By: robbert

Differential Revision: D1136491
2014-01-22 12:47:53 -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
Sara Golemon b413c90e23 Tabs, not spaces 2013-10-16 11:16:10 -07:00
Sara Golemon c29787e69a Disable libnuma support (for now)
See comment in hphp/util/CMakeLists.txt for explanation of why
2013-10-16 10:12:09 -07:00
Sara Golemon 5cae789c57 Simplify HHVM_LINK_LIBRARIES 2013-10-16 09:48:41 -07:00
Eugene Letuchy bc847b8522 make ()-invoke work on array callables (jit)
JIT counterpart to {D984939}. Relies on a similar
 partially-populated JIT-allocated ActRec passed to a C++ helper
 technique used by methodCacheSlowPath.

Reviewed By: @jdelong

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

Reviewed By: @elgenie

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

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

Reviewed By: @andralex

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

Reviewed By: @paroski

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

Reviewed By: @jano

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

Reviewed By: @paroski

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

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

Reviewed By: @bertmaher

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

Reviewed By: @markw65

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

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

Reviewed By: @elgenie

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

Reviewed By: @JoelMarcey

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

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

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

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

Add a count of tests that will be compared.

Reviewed By: @ptarjan

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

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

Reviewed By: @oyamauchi

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

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

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

Reviewed By: @jano

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Closes #1165

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Closes #1173

Reviewed By: @edwinsmith

Differential Revision: D1011297

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

Closes #1170
Closes #1175

Reviewed By: @markw65

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

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

Reviewed By: @swtaarrs

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

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

Reviewed By: @swtaarrs

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

Reviewed By: @JoelMarcey

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

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

Reviewed By: @JoelMarcey

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

Reviewed By: @alexmalyshev

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

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

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @jdelong

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

Reviewed By: @scannell

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

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

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @scannell

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

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

Reviewed By: @JoelMarcey

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

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

Reviewed By: @dariorussi

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

Closes #1168

Reviewed By: @JoelMarcey

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

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

Reviewed By: @dariorussi

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

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

Reviewed By: @paroski

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @bertmaher

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

Reviewed By: @swtaarrs

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

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

Reviewed By: @dariorussi

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

Reviewed By: @alexmalyshev

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

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

Reviewed By: @swtaarrs

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

Reviewed By: andrii

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

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

Reviewed By: andrii

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

Reviewed By: @dariorussi

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

Reviewed By: @jdelong

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

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

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

Reviewed By: @jdelong

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

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

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

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

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

Reviewed By: @jdelong

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

Reviewed By: @dariorussi

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

Reviewed By: bertrand

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

Reviewed By: @ottoni

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

Closes #1158

Reviewed By: @JoelMarcey

Differential Revision: D1007352

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

Reviewed By: @swtaarrs

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

Reviewed By: @dariorussi

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

Reviewed By: @mikemag

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

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

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

Reviewed By: @ottoni

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

Reviewed By: @ottoni

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

Reviewed By: @sgolemon

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

Reviewed By: @swtaarrs

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

Reviewed By: @bertmaher

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

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

@EntNotFoundException

Reviewed By: @ptarjan

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

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

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @ptarjan

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

Reviewed By: @kmafb

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @JoelMarcey

Differential Revision: D1005290

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

I also upgraded composer while I was in there.

Reviewed By: @JoelMarcey

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

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

Reviewed By: @paroski

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

This is for a fatal in Laravel.

Reviewed By: @JoelMarcey

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

Reviewed By: @edwinsmith

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

Closes #1009
Closes #1149

Reviewed By: @markw65

Differential Revision: D1004416

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

Reviewed By: @swtaarrs

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

Reviewed By: @jdelong

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

Closes #1140

Reviewed By: @markw65

Differential Revision: D1000998

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

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

Reviewed By: @jdelong

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

Reviewed By: andrii

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

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

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

Reviewed By: @ottoni

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

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

Closes #1144

Reviewed By: @JoelMarcey

Differential Revision: D1003188

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

Closes #1143
Closes #1145

Reviewed By: @JoelMarcey

Differential Revision: D1003269

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

Reviewed By: @JoelMarcey

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

Reviewed By: @bertmaher

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

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

TODO:

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

Reviewed By: @paroski

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

Reviewed By: @swtaarrs

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Closes #1139
Closes #1142

Reviewed By: @JoelMarcey

Differential Revision: D1000995

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

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

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @swtaarrs

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

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

Reviewed By: @swtaarrs

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

Reviewed By: @elgenie

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @bertmaher

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

Reviewed By: @andralex

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

Reviewed By: @andralex

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

Reviewed By: @markw65

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @ottoni

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

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

Reviewed By: @scannell

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: zhuohuang

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

Reviewed By: @edwinsmith

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

Reviewed By: @bertmaher

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

Reviewed By: @bertmaher

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

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

  - make Class::wouldCall a non-member function

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

  - the start of some documentation about what it is

Reviewed By: @markw65

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @elgenie

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

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @ottoni

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

Reviewed By: @markw65

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

Reviewed By: @scannell

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

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

Reviewed By: @ptarjan

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

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

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @mikemag

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

Reviewed By: @edwinsmith

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

Reviewed By: @sgolemon

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

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

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

Example output: P2777440

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

Reviewed By: @ptarjan

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

Reviewed By: @bertmaher

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

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

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

Reviewed By: @scannell

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @ptarjan

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

Reviewed By: bertrand

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

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

Reviewed By: bertrand

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

Closes #1121

Reviewed By: @ptarjan

Differential Revision: D993915

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

Reviewed By: bertrand

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

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

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

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @mikemag

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

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

Closes #1051
Closes #1112

Reviewed By: @ptarjan

Differential Revision: D990460

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

Reviewed By: @andralex

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

Closes #1105

Reviewed By: @ptarjan

Differential Revision: D989566

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

Reviewed By: @jdelong

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

Opensource commit message:
Moving VariantController into a separate file.

Reviewed By: zhuohuang

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

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Destroy!

Reviewed By: @jdelong

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

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

Reviewed By: @jdelong

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

Closes #1090

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @edwinsmith

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

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

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

Reviewed By: @edwinsmith

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

Closes #837
Closes #1110

Reviewed By: @ptarjan

Differential Revision: D989689

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

Closes #1115
Closes #1117

Reviewed By: @JoelMarcey

Differential Revision: D991348

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

Closes #1113
Closes #1114

Reviewed By: @JoelMarcey

Differential Revision: D990897

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

Closes #1020

Reviewed By: @markw65

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

Reviewed By: @ottoni

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

Closes #1106

Reviewed By: @ptarjan

Differential Revision: D989582

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

Reviewed By: @paroski

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

Reviewed By: @scannell

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

Reviewed By: @ottoni

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

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

Reviewed By: @jdelong

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

Reviewed By: @sgolemon

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

Reviewed By: @alexmalyshev

Differential Revision: D989609

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

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

Reviewed By: @mikemag

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

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

Reviewed By: @scannell

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

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

Reviewed By: drussi

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

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

Reviewed By: @jdelong

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

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

Reviewed By: @jdelong

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

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

Reviewed By: @swtaarrs

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

Reviewed By: @jdelong

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

Reviewed By: @ptarjan

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

Fixes the last fatal in the composer unittest suite.

Reviewed By: @ptarjan

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

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

This fixes a fatal in Symfony unit tests.

Reviewed By: @ptarjan

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

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

Reviewed By: @jdelong

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

Reviewed By: @ottoni

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

Reviewed By: @jdelong

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

Reviewed By: @swtaarrs

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @paroski

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

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

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

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

Reviewed By: bertrand

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

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

Reviewed By: @swtaarrs

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

Closes #1085

Reviewed By: @markw65

Differential Revision: D980178

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

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

Reviewed By: @swtaarrs

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

zend unit test failing - not connected to this code

Reviewed By: bmaurer

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

Reviewed By: @ptarjan

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

Reviewed By: @ptarjan

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

Closes #1087

Reviewed By: @JoelMarcey

Differential Revision: D982028

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

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

Reviewed By: bertrand

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

Reviewed By: @markw65

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

Closes #1081

Reviewed By: @markw65

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

Reviewed By: @markw65

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

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

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

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

Reviewed By: @swtaarrs

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

Reviewed By: @jdelong

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

Future updates:

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

Reviewed By: @sgolemon

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

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

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @ptarjan

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

Reviewed By: @mikemag

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

Reviewed By: bertrand

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

Reviewed By: @scannell

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

Reviewed By: @paroski

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

Reviewed By: @paroski

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

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

Reviewed By: @ptarjan

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

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

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

Reviewed By: @paroski

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

Reviewed By: @paroski

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

Reviewed By: @paroski

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

Reviewed By: @paroski

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

Reviewed By: bmaurer

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

Reviewed By: @paroski

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @hermanventer

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

Reviewed By: @markw65

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

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

Reviewed By: @jdelong

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

Reviewed By: @andralex

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

Reviewed By: @elgenie

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

Reviewed By: @andralex

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

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

Reviewed By: drussi

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

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @paroski

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

Reviewed By: @ptarjan

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

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

Reviewed By: @mikemag

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

Imagine this example:

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

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

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

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

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

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

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

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

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

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

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

Reviewed By: bertrand

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

Reviewed By: @elgenie

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

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

Storing a Transport * in ServerTaskEvent instead of a Resource

Template; expose the Transport type from the Server

Also parametrize the Transport class

Expose XboxTransport

Reviewed By: @jano

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

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

Reviewed By: @elgenie

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

Reviewed By: @ptarjan

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

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

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

Reviewed By: @jdelong

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

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

 As opposed to the current:

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

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

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

Reviewed By: @paroski

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

Reviewed By: julk

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @sgolemon

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

Reviewed By: @edwinsmith

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

Closes #1077

Reviewed By: @sgolemon

Differential Revision: D976401

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

Closes #1076

Reviewed By: @markw65

Differential Revision: D975429

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

Reviewed By: @jdelong

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

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @ptarjan

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

Reviewed By: @andralex

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

Reviewed By: @paroski

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

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

I'll fix it but reverting it for now

Reviewed By: @elgenie

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

Reviewed By: @scannell

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

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

Reviewed By: bmaurer

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

Reviewed By: @ptarjan

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

Reviewed By: @meyering

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

Reviewed By: @ptarjan

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

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

Reviewed By: @ptarjan

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

Reviewed By: @markw65

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

Reviewed By: drussi

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

Reviewed By: @jdelong

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

Reviewed By: @swtaarrs

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

Reviewed By: @elgenie

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

 Needed for {D964614}

Reviewed By: @paroski

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

Reviewed By: @paroski

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

Reviewed By: @paroski

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

Closes #1067
Closes #1069
Closes #1074

Reviewed By: @ptarjan

Differential Revision: D974502

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

Reviewed By: @markw65

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

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

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

Reviewed By: @paroski

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

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

Reviewed By: @paroski

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

Closes #504
Closes #1061

Reviewed By: @ptarjan

Differential Revision: D972519

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @paroski

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

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

Future:

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

New Files for this diff:

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

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

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

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

Reviewed By: @ptarjan

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

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

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

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

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

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

Reviewed By: @ptarjan

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

Reviewed By: @markw65

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

Reviewed By: @ptarjan

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

Reviewed By: @ptarjan

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

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

Reviewed By: @jdelong

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

Closes #787
Closes #1046
Closes #1047

Reviewed By: @jdelong

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

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

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

Reviewed By: @ottoni

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

Closes #1056
Closes #1057

Reviewed By: @ptarjan

Differential Revision: D970665

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

Reviewed By: @jdelong

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

Closes #1063

Reviewed By: @ptarjan

Differential Revision: D971664

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

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

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

Reviewed By: @ottoni

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

Reviewed By: @ptarjan

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

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

Reviewed By: @mikemag

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

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

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

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

.

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

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

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

Reviewed By: @jdelong

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

Reviewed By: @meyering

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

Reviewed By: @meyering

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

Reviewed By: bmaurer

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @elgenie

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

Reviewed By: @edwinsmith

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

Reviewed By: drussi

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

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

Reviewed By: @edwinsmith

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

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

Reviewed By: bertrand

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

Reviewed By: @jdelong

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

Reviewed By: @JoelMarcey

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

Reviewed By: @jano

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

Reviewed By: @andralex

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

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

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

Closes #1058

Reviewed By: seanc

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

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

Reviewed By: bertrand

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

Reviewed By: @markw65

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

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

Reviewed By: @markw65

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

Reviewed By: @paroski

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

Reviewed By: @jdelong

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

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

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

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

Reviewed By: @jdelong

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

Reviewed By: @hermanventer

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

Reviewed By: @swtaarrs

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

Reviewed By: @hermanventer

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

Reviewed By: @swtaarrs

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

Reviewed By: @mikemag

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

Reviewed By: @ptarjan

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

Reviewed By: @edwinsmith

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

Reviewed By: @markw65

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

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

Reviewed By: @jdelong

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

Reviewed By: alikhtarov

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Catch invalid property and raise like Zend.

Reviewed By: @ptarjan

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

Reviewed By: @swtaarrs

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

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

Closes #190

Reviewed By: @markw65

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

Reviewed By: @paroski

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

Reviewed By: @mikemag

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

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

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Reviewed By: @ottoni

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

Reviewed By: @jdelong

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

Reviewed By: @ptarjan

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

Reviewed By: @ptarjan

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @sgolemon

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

Reviewed By: @andralex

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

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

Reviewed By: @markw65

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

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

Reviewed By: @jdelong

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @ptarjan

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

Reviewed By: drussi

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

Reviewed By: @jdelong

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

Reviewed By: @jdelong

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

Closes #1006

Reviewed By: @ptarjan

Differential Revision: D953349

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

Reviewed By: @jdelong

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

Reviewed By: @markw65

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

Reviewed By: @markw65

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

Reviewed By: @jdelong

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

Reviewed By: @ptarjan

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

Reviewed By: @jdelong

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

Reviewed By: andrii

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

Reviewed By: @edwinsmith

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

Reviewed By: @edwinsmith

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

Reviewed By: @oyamauchi

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

Reviewed By: @jdelong

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

Reviewed By: @sgolemon

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

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

Reviewed By: @sgolemon

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

Reviewed By: @sgolemon

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

Reviewed By: @sgolemon

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

Reviewed By: @markw65

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

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

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

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

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

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

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

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

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

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

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

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

Closes #849
Closes #1032

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

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

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

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

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

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

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

Closes #1031

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

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

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

Closes #1022

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #1021

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

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

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

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

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

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

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

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

There are a couple things left to do:

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

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

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

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

Closes #990

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

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

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

Closes #1015

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #1001

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

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

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

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

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

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

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

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

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

Hooks internal functions:

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

When registered during Extension::moduleLoad() with:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #1000

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

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

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

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

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

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

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

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

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

Closes #996

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

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

Closes #963

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Lets make it the same timeout as the script itself.

Differential Revision: D945165
2013-08-29 11:58:40 -07:00
mwilliams 6a87dbf1e5 Revert "g++-4.8.1"
This reverts commit 7d94e20daede9ab6fa1d3bdc6f0a03477a631efc.

Some tests are breaking in the opt build.

Differential Revision: D946629
2013-08-29 11:58:40 -07:00
mwilliams 4accc0496c Fix a crash in Unit::compactMergeInfo
If redoHoistable is set, at least one defClass failed,
so we can't compact the unit.

This should prevent crashes - but something must have gone wrong
to get into this state. An AttrUnique class should never fail
to be defined.

Differential Revision: D946531
2013-08-29 11:58:39 -07:00
Emil Hesslow a62bf121a5 Fix clone of SplPriorityQueue
Clone the underlying _SplPriorityQueueHeap object when someone clones a SplPriorityQueue object

Closes #984

Differential Revision: D942743
2013-08-29 11:58:39 -07:00
bsimmers a66d7818ce Disable fread_socket_variation1.php
I've seen it fail on a few completely unrelated diffs

Differential Revision: D945745
2013-08-29 11:58:39 -07:00
Jordan DeLong 42f7e857f6 Move fCallArrayHelper to an asm helper stub
fCallArrayhelper smashes its return address, leading to
return branch mispredictions until we return enough times to get back
on track.  Rewrite it as an asm stub so it can make a tail jump and
pop the proper return ip into the ActRec.

Differential Revision: D941930
2013-08-29 11:58:38 -07:00
Jordan DeLong 9f08515ad4 Don't leave out AttrPhpLeafFn on account of FCallArray
FCallArray does a stack overflow check as part of its
"mini-prologue", so we can still consider functions that use it leaf
functions.

Differential Revision: D940120
2013-08-29 11:58:38 -07:00
Mike Magruder 84d1d995d0 Fix bugs when multiple threads hit the same breakpoint
The function blockUntilOwn() was not actually blocking threads before letting them into processInterrupt(), which allowed multiple threads hitting breakpoints to process their interrupts and communicate with the client, which is bad.

Also fixed an issue where interrupts processed during an eval would result in erasing the current thread's 'lock' on processing interrupts, resulting in the same issue.

Differential Revision: D945203
2013-08-29 11:58:37 -07:00
Sean Cannella 2dcf721cea fix namespace bugs in ext_class/ext_reflection
- ext_* functions that call Unit::lookupClass were not correctly
handling denormalized names (ex. \FooNS\Bar), this adds a wrapper for
this pattern and calling it.
- ReflectionClass::subclassOf should be using f_is_subclass_of

Closes #827

Differential Revision: D945363
2013-08-29 11:58:37 -07:00
mwilliams da668c3500 g++-4.8.1
Switch to g++-4.8.1

Differential Revision: D935591
2013-08-29 11:58:36 -07:00
Markus Staab eaba93f75b adjust ArrayIterator internals for zend parity
HHVM's current implementation promotes internal state to possible
subclasses.

This is meant as preparation to support RegexIterator in a separate
commit, because the Zend tests rely heavily on the internal var-dump
representation of ArrayIterator.

Closes #989

Differential Revision: D943461
2013-08-29 11:58:36 -07:00
Daniel Sloof ed5a9dc09f make simplexml xpath return original objects
Currently, xpath just creates new elements. This means that any
modification done to the return object will not change its original
parent.

xpath can also traverse -up- the hierarchical node tree, so we cannot
just recursively go through children to find a matching node. this is
why an additional m_root was introduced, to keep track of the root node
of the current tree.

Closes #986

Differential Revision: D943404
2013-08-29 11:58:36 -07:00
bsimmers 77dea1bdd0 Temporarily remove Iterable's function declarations
D923036 added these but we're not quite ready. Take them out for now.

Differential Revision: D944660
2013-08-29 11:58:35 -07:00
bsimmers d4dbe54e59 Fix region_tracelet test
The tracelet region selector was relaxing a guard that the normal
translator wasn't, exposing a bug in the register allocator: when a load
instruction has a label we care about its type, so we can't assign it to an xmm
register. We really shouldn't be guarding on this load at all, but that can be
fixed in a separate diff.

Differential Revision: D944937
2013-08-29 11:58:35 -07:00
Jordan DeLong 4b8304f07a Remove try/catch in conv{Obj,Res}ToStrHelper
We have a catch trace that does a SpillStack for both of
these helpers.  Incidentally, zend raises a fatal if you try to throw
in this situation.

Differential Revision: D944079
2013-08-29 11:58:34 -07:00
Jordan DeLong 3a2194c88d Implement StringData::initAttach in terms of initCopy
This seems reasonable.

Differential Revision: D938745
2013-08-29 11:58:34 -07:00
Rachel Kroll fe9d608898 Test a few paths through FileCache
Start testing FileCache

Differential Revision: D944350
2013-08-29 11:58:33 -07:00
Jordan DeLong dd8a4fd6b7 Some cleanup on HPHP::CstrBuffer
Don't use DECLARE_BOOST_TYPES (use make_shared where
appropriate).  Delete the broken (double-free) default copy
constructor and copy assignment operator.  Also document some things
because a few points are more subtle than they seemed (unlike
StringBuffer, most functions have a precondition that the buffer is
valid, and the filename constructor does not report errors).

Differential Revision: D931752
2013-08-29 11:58:33 -07:00
Dario Russi 55f3a63d54 inline vector/pair get and vector set
Define new OpCodes to allow code generation for vector style get and set

Differential Revision: D905624
2013-08-29 11:58:33 -07:00
Paul Tarjan 61543666b9 fix test paths and import extra files to bad
@WizKid has been doing a few diffs on HHVM recently and he noticed that the path of the errors didn't match zend. This is totally right and I was being dumb trying to emulate the old perl script for our paths. Instead we should just match %s.

I also noticed you can't just run the bad tests from their directory since sometimes they need an `.inc` file. We should just duplicate those files in there so you can run the bad tests directly.

Differential Revision: D943288
2013-08-29 11:58:32 -07:00
Alok Menghrajani 7202c3d569 Rename the magic "__resource" class to "resource"
www engineers would like to be able to provide the type for code which
takes a resource as input. This simple change is a first step in the right direction.

In the future, we might want to provide a way to specific the exact type of resource
(e.g. PlainFile vs CurlHandle).

Differential Revision: D873115
2013-08-29 11:58:28 -07:00
huzhiguang d6f4be7d07 Fix libevent keepalive memery leak
Closes #997
2013-08-29 10:09:15 -07:00
Sara Golemon 8f6c166d5b Update folly 2013-08-29 09:58:34 -07:00
Sara Golemon 2960debf8f Hide composer expiration warning 2013-08-28 16:30:28 -07:00
Sara Golemon 825db91e22 Update Folly 2013-08-28 15:12:23 -07:00
Jordan DeLong 981c510eb2 Delete the rest of the litstr comparison ops
I want to remove StackStringData, and these were some of the
uses remaining.

Differential Revision: D935951
2013-08-27 11:58:31 -07:00
Jordan DeLong 64ca1fc194 Clean up StringBuffer a bit
Privatize several public functions, remove some redundant
functions, make some things non-members (appendJSONEscape), remove
DECLARE_BOOST_TYPES, and document contracts; also some gratuitous
style changes.  I was initially planning to make it include the null
in its capacity, but since capacity is not exposed anywhere I think
it's fine as is.  (And eventually we don't want to require the null
when handing off to String---only when people call data()---but that
is a separate project.)

Differential Revision: D931746
2013-08-27 11:58:31 -07:00
bsimmers 134a0d79bb Support specialized types in the tracelet region selector
Most of the hard work to support specialized types was getting guard
relaxation working, so this diff is pretty straightforward. The only big change
is collapsing GuardCls and GuardArrayKind back into GuardLoc. If that turns out
to be a noticeable perf regression I can investigate other options.

Differential Revision: D936145
2013-08-27 11:58:30 -07:00
bsimmers 599a2cacd3 Make hhir guard relaxation less conservative
This diff expands guard relaxation to relax all eligible
guards, not just guards for values that are never read. Specialized
types are still not supported yet; the tracelet region selector drops
all specializations.

Differential Revision: D934157
2013-08-27 11:58:30 -07:00
Edwin Smith 21795c5415 Move util/vixl up one level
Giving each lib/exe build target its own toplevel dir.

Differential Revision: D943470
2013-08-27 11:58:30 -07:00
Sara Golemon ea0a7f6636 Get rid of errant double-license 2013-08-27 11:58:30 -07:00
Paul Bissonnette b913a5d9a5 Generalized Inlining
Generalizing inlining to work with more complex functions.

Differential Revision: D898434
2013-08-27 11:58:30 -07:00
Edwin Smith 4a0c336da6 Move util/parser up one level.
It defines its own library, make it a peer with other libs.

Differential Revision: D943071
2013-08-27 11:58:30 -07:00
Joel Marcey 849db6b623 Implement ReflectionMethod::setAccessible()
The unit tests for Composer require a call to ReflectionMethod::setAccessible(). This implements that method.

Differential Revision: D939166
2013-08-27 11:58:29 -07:00
Edwin Smith 4c638d419e Move util/neo up one level
It defines its own library, remove the unnecessary nesting.

Differential Revision: D943068
2013-08-27 11:58:29 -07:00
Guilherme Ottoni 66a48e178e Fix get_class_methods() to include trait methods
get_class_methods() was not including methods that came from traits.
This diff changes get_class_methods() to look at the Class' method
table, instead of the PreClass.  With this approach, we could avoid
traversing the inheritance hierarchy.  However, that changes the order
of the methods in the resulting array.  So, in order to preserve the
order, this diff still traverses the inheritance hierarchy, and
methods are added to the array when visiting the class that declared
them.

This modification changed the order of methods for some "quick" tests
with classes derived from builtin classes.  However, hhvm was not
matching Zend on these tests already, so I updated them.

Differential Revision: D940214
2013-08-27 11:58:29 -07:00
Owen Yamauchi 88cd96db87 Devirtualize ObjectData, part 1
The C++ vtable pointers and the m_cls pointers in ObjectData are
redundant for C++ extension classes; they both indicate the ObjectData's
dynamic type.

This diff gives ObjectData the same treatment that the ArrayData
hierarchy got, replacing virtual functions with manual dispatch based on
attributes and m_cls. We can't do direct comparison against m_cls,
because of inheritance, except when we know inheritance is not in the
picture.

The vtable isn't gone yet, because I need to do something about C++
destructors, which still require virtual dispatch. That's going to
require a lot of grunt work, so I wanted to put this diff up to keep
that stuff separate.

I did, however, make ~ObjectData non-virtual and try to compile, to
flush out all the dynamic_casts of ObjectData.

- The type-casting functions and clone() are pretty straightforward. The
  only trick is that specialized clone() functions now have to call
  cloneImpl() instead of the base class' clone(), otherwise infinite
  recursion. I added an ObjectData attribute to indicate whether clone()
  is special.

- t___{sleep,wakeup} didn't even need to be virtual, it turns out.
  ObjectData's implementation goes through the normal PHP-method lookup
  path, which effectively does virtual dispatch and routes us to any
  specialized implementations anyway.

Differential Revision: D940852
2013-08-27 11:58:28 -07:00
Edwin Smith fd881ac637 Rename _ to - in hphp/util
One more step in the renaming arc.
Depends on D925182

Differential Revision: D927227
2013-08-27 11:58:28 -07:00
Sean Cannella 84e61d1f94 Merge pull request #994 from staabm/apt_fast
speedup travis ci build using apt-fast and paralleled downloads
2013-08-27 11:16:19 -07:00
Markus Staab 0b2dfdf449 run all downloads in background and in parallel 2013-08-27 14:31:12 +02:00
Markus Staab 4add8586c5 use apt-fast instead of apt-get to speedup build 2013-08-27 12:40:07 +02:00
Edwin Smith 2dea04cf9b Use StringData::same() in a few more places to reuse code.
Now that same() has a faster comparison loop than memcmp,
use it in a couple more places.

Differential Revision: D942902
2013-08-26 09:21:41 -07:00
Bert Maher a24fbde50b Refactoring member-operations so each kind of base has its own function
I liked the results of some cleanup of SetNewElem, so I
decided to extend it to many of the other Elem* functions in
member-operations.h.  This diff really just moves code around to make
it easier to experiment with in the future.

Differential Revision: D932351
2013-08-26 09:21:40 -07:00
Edwin Smith 15dc5b0221 Use "Packed" as the term for vector-like arrays.
The term Vector is getting too overloaded in our codebase.  Rename
vector-like array kinds to "packed" instead.

Differential Revision: D935245
2013-08-26 09:21:40 -07:00
Emil Hesslow 94e49318e4 Handle $a[] = 1
- This is how Zend does it. If $index is null treat it as no $index at all

Differential Revision: D943043
2013-08-26 09:21:39 -07:00
Emil Hesslow 1d660802c2 Add CachingIterator
- Implement CachingIterator
- I ran the idl/sysdoc.php script on my file but it didn't do anything to it
- I started with https://github.com/php/php-src/blob/master/ext/spl/internal/cachingiterator.inc and then added everything that it was missing
- Some of the documentation at http://www.php.net/manual/en/class.cachingiterator.php is strange. All the offset function say that they take string arguments. But the class implements ArrayAccess which specify the arguments as mixed. So I went with mixed because otherwise I got a fatal
- I moved over all bad tests that are now passing
- The rest of the bad tests that test CachingIterator are passing too. It is just that error messages are different so I can't move them to good

Differential Revision: D942889
2013-08-26 09:21:39 -07:00
Drew Paroski f3da1ade07 Fix gettype() for resources
Differential Revision: D941144
2013-08-26 09:21:38 -07:00
Edwin Smith 47d8ee5298 Remove Array::addLval() methods, use lvalAt() instead.
The AddLval methods were fairly cold, so reimplement them in
terms of lval(), but preserve the assert that ensures the keys
being added do not already exist.  This reduces the number
of kind-specific methods we need to implement.

Added Array::setWithRef(key,value) to capture a common use
case for lvalAt().  Later this can implemented more efficiently
as a virtual method in ArrayData subclasses.

Differential Revision: D937227
2013-08-26 09:21:38 -07:00
Jordan DeLong 09d0dbf15c Fix nemo issue (BadArgumentType) for type aliases to non-objects
At call sites, it was complaining because it thought an alias
parameter must be a name of an object.  Also make a function less
nested.

Differential Revision: D942157
2013-08-26 09:21:37 -07:00
Jordan DeLong 7cc3516b8f Change StringSlice to take a uint32_t instead of an int
StringSlice{foo, bar} where bar is uint32_t produces an error
(in 4.7.1, 4.6 doesn't have this part of C++11 correct yet).

Differential Revision: D938436
2013-08-26 09:21:37 -07:00
Jordan DeLong 43c7e09579 Fix type aliases for function types
They were just broken.  Right now, even evaluating a unit
that is declaring one just leads to attempting to autoload the empty
string as a type alias (since it thinks the type alias was
KindOfObject).  Changes them so they work just like normal <?hh
function typehints (currently unchecked).

Differential Revision: D942768
2013-08-26 09:21:36 -07:00
Drew Paroski e0775ce8b6 Fix list assignment with collection literals
Doing "list($x,$y) = Vector {1,2}" should work. Make it so.

Differential Revision: D940987
2013-08-26 09:21:36 -07:00
Drew Paroski 9c2223e9c7 Support "tuple(..)" in initializer expressions
Differential Revision: D940814
2013-08-26 09:21:35 -07:00
Drew Paroski ed680695ea Improve 'string key not present' exception message for collections
At present the 'string key not present' exception message can be misleading
when the string key is truncated (which happens when the string key exceeds
20 characters) and this has caused some confusion.

This diff improves the exception message in two ways. First, the string key
will only get truncated when the key exceeds 100 characters. Second, the
exception message will make it clear when the string was truncated by
printing "(truncated)" after the string key.

Differential Revision: D940984
2013-08-26 09:21:13 -07:00
mwilliams 00ec2d1971 Reinstate fb_setprofile
Its the only way we have for reliably testing hard to repro edge
cases (such as timeouts during FunctionEnter/FunctionExit) and I find it
very useful for debugging complex code.

Differential Revision: D941226
2013-08-26 09:21:13 -07:00
Sara Golemon 92641497cc Fix Zend string_crypt() to report failures properly
strdup(crypt_r()) can result in a segfault
if crypt_r() returns null.

Closes #983

Differential Revision: D940753
2013-08-26 09:21:12 -07:00
Mike Magruder bdf3493274 Fix generator-related errors in PHProf output
Fire EventHook::FunctionExit() in the correct places for generators. This was happening during Continuation destruction, which is quite a while after we exit the continuation, and causing double notifications for continuation exits. Also fire the event when unwinding out of a generator, since that one was missing.

Differential Revision: D939893
2013-08-26 09:21:11 -07:00
Sean Cannella 60d247d450 HHVM should compile with libmemcached 1.0.9+
libmemcached 1.0.8 broke the memcache/memcached extensions. It
is also missing some API support we need, so this should unbreak us as
of 1.0.9+. 1.0.8 plain won't work but earlier and later will.

Closes #934
Closes #973

Differential Revision: D939850
2013-08-26 09:21:10 -07:00
Edwin Smith 3df3ce4f15 Move util/zend (which defines zend.a) up one level.
And rename _ to - while we're at it.

Differential Revision: D925182
2013-08-23 11:24:47 -07:00
Drew Paroski 6d87dee498 Support "(new Vector {..})->method()" style syntax
This diff adds support for calling methods directly on collection literal
expressions (as long as the collection literal is wrapped in parentheses).

Differential Revision: D940562
2013-08-23 09:59:53 -07:00
Sean Cannella 9bdf60c0a9 ReflectionProperty(null,null) should throw
ReflectionProperty constructor should reject nulls

Closes #975

Differential Revision: D939337
2013-08-23 09:59:29 -07:00
Daniel Sloof d2981f6f81 fallback to default separators in number_format
When number_format receives 'null' for one of its separator parameters,
we must pass it back to t_number_format so it can decide whether or not
it should fallback to its default separators.

Currently, when passing NULL to a parameter that is defined as String,
it is implicitly converted to an empty string, and subsequently
str.isNull() will return false.

Instead, we use a Variant with a default string value.

Closes #982

Differential Revision: D940482
2013-08-23 09:59:28 -07:00
Sara Golemon 00908f8be3 Reduce bad error spam on too few arguments
function foo($bar, $baz) { }
  foo();

Currently raises two errors:

  foo() expects exactly 2 parameters, 0 given
  foo() expects exactly 2 parameters, 1 given

Only the first of these is either meaningful or correct.
Stop reporting once we've raised it.

Differential Revision: D939810
2013-08-23 09:59:27 -07:00
Simon Welsh f9d0c1128a use trigger_error in PHP for Redis user errors
- trigger_error is intended for reporting user errors, not
error_log

Closes #970

Differential Revision: D937921
2013-08-23 09:59:27 -07:00
Sean Cannella af07c475f5 move more helpers out of code-gen
Move more stateless platform dependent and agnostic helpers out of
code-gen.cpp

Differential Revision: D936727
2013-08-23 09:59:26 -07:00
Daniel Sloof 7a8c8474ec multiple simplexml fixes
- multiple fixes for simplexml required by magento

Closes #790
Closes #819
Closes #955

Differential Revision: D925428
2013-08-23 09:59:25 -07:00
Mike Magruder 0db30b9e10 Remove some dead profiling code
This profiling path was unused after D894723. Removing it.

Differential Revision: D934477
2013-08-23 09:59:25 -07:00
Markus Staab fe6cfe9fa3 fixed serialize/unserialize for SplObjectStorage
added error handling for bad serialized strings according to zend tests.
We cannot move the actual tests from "bad" to "good" because ATM they
rely on the internal serialized string format of SplObjectStorage, which
is not yet reimplemented.

Closes #969

Differential Revision: D935251
2013-08-23 09:59:24 -07:00
Mirek Klimos fb53e8c8a5 Parser refactorings: onFunction/onMethod/onClosure
We have separate methods for parsing functions and methods
(onFunction/onMethod), which have a lot in common. On the other
hand, onClosure just calls onFunction with a special parameter
that modifies its behavior. Lets make this more consistent and
remove the duplicated code.

Differential Revision: D934034
2013-08-22 12:40:20 -07:00
Edwin Smith 666fa474ff Optimize string same() and hitStringKey()
Most strings used as keys are either small or not shared, where the
data pointers cannot be equal.  Of the rest (shared), most could have
been small.

This diff copies small SharedVariant strings, so they don't refer
back to the SharedVariant, and don't need to be enlisted.  Then,
this changes hitStringKey() to not check data pointers, making it
equivalent to StringData::same().  Lastly, hand-write the comparison
loop in StringData::same() so we compare words at a time, and the
loop can be inlined.

Differential Revision: D937233
2013-08-22 12:40:19 -07:00
Joel Marcey c877f4b737 Implement ReflectionParameter::IsCallable()
The Facebook SDK unit tests fataled because ReflectionParameter::IsCallable() was not implemented. So, this implements it. Now the unit tests pass. Bad zend test now passes!

closes #931

Differential Revision: D938769
2013-08-22 12:40:19 -07:00
bsimmers 5d16068921 Rename VectorTranslator to MInstrTranslator
Vector has become too overloaded in this codebase. MInstrTranslator is
more accurate anyway; we have multiple different types of hhbc opcodes with
immediate vectors that aren't m-instrs.

Differential Revision: D935859
2013-08-22 12:40:18 -07:00
Mirek Klimos fd7f000649 Prerequisites for eager execution of async functions
Here's a few minor changes in emitter that will be needed later for
eager execution of async functions. Just to make the upcoming diff
sipmler.

Differential Revision: D935301
2013-08-22 12:40:17 -07:00
Edwin Smith 6d43cf6ef5 Add DataTypeProfiler
You can use this anywhere to sample the DataTypes at a particular
point in the code, for example calls to JIT helpers.

Differential Revision: D925193
2013-08-22 12:40:17 -07:00
Eric Caruso 07aaeff5ec Improve error message for post-try blocks which are not finally
Currently, hhvm interprets post-try blocks not necessarily
beginning with an actual finally token as finally blocks, and thus
produces an error message to the user telling them finally blocks
are disabled even if they misspelled something, for example.

This moves things so the "finally disabled" message only comes up
if you enter a syntactically valid finally block.

Differential Revision: D918867
2013-08-22 12:40:16 -07:00
Jordan DeLong d5ae3d1bbe Make new stack_overflow test more tolerant
In contbuild it's failing on line 5 instead of 6.

Differential Revision: D937472
2013-08-22 12:40:11 -07:00
Edwin Smith e54b0dc4a9 Do not check for self in assignValHelper.
It should be almost never true, and the assignment code is
already safe for self-assignment.  Note if Variant V == uninit,
then V=V now converts to null, unlike before.  IMHO this is
a bugfix but I don't know that we've seen it in the wild.

Differential Revision: D933229
2013-08-21 09:33:14 -07:00
Edwin Smith 288d4993e2 Remove allocElmFast; its only called in one place.
It used to have two callsites before the vector code landed.

Differential Revision: D932789
2013-08-21 09:33:13 -07:00
Emir Habul 7d03ed4284 hphp: Instance ID for controlled stopping of server
When port-takeover is used, new instance of the process will be started but
something can call stop command for the old task. Given how `localhost:9099/stop?`
can affect hhvm that was just started, I want to limit stop command to be
specific to an instance ID.

This instance ID could be a random number, or container uuid of LXC.

Differential Revision: D932953
2013-08-21 09:33:12 -07:00
mwilliams 9e35396b7f Fix some stack overflow bugs
If re-entry triggers stack overflow, there is no FCall or FCallArray,
so the code to find the pc in REQ_STACK_OVERFLOW would fail. If it
managed to get through there, it would then try to DecRef the contents
of an ActRec, sometimes causing it to DecRef a Func.

In addition, if a "leaf" function resulted in re-entry we didn't
necessarily check the stack.

Differential Revision: D936843
2013-08-21 09:33:12 -07:00
bsimmers 8653894f94 Trim down test/slow/ext_network
It's flaky because it depends on external servers
responding. Remove those bits.

Differential Revision: D935602
2013-08-21 09:33:11 -07:00
mwilliams 4c5adad866 Fix a crash destroying Funcs
Func::destoy needs to block on getting the write lease, so it
can smash the function prolog.

Also, the prolog array in cloned closures is used to redispatch to
the translation corresponding to the clone, since we never enter
such functions via their prolog. Since its not a true prolog, we
shouldn't smash it.

Differential Revision: D933704
2013-08-21 09:33:10 -07:00
Markus Staab d400153b21 move SplObserver tests from bad to good
move basic tests for SplObserver

Closes #968

Differential Revision: D935248
2013-08-21 09:33:10 -07:00
bsimmers 52e16a280c Add basic guard relaxation to hhir
This diff implements basic guard relaxation in hhir. Whenever we read
a local or pop/peek at HhbcTranslator's EvalStack, a DataTypeCategory is
specified. The source of the value is traced back as far as possible, and if we
end up at a guard instruction, the constraint for that guard is updated
appropriately. After IR generation, a pass is run to change the types of these
guard instructions to the least specific type allowed by their constraint. This
is currently only used to eliminate completely unused guards in the tracelet
region selector, so all the guards are either DataTypeGeneric or
DataTypeSpecific.

Differential Revision: D924955
2013-08-21 09:33:10 -07:00
Paul Saab 04b77176fe Fix sockopen_impl with IPv6 addresses
sockopen_impl requires IPv6 addresses be enclosed in brackets.

Differential Revision: D927309
2013-08-21 09:33:09 -07:00
tmulchay b5ae1aab3a Fixing typo in zRevRange function
The zRevRange function argument $withscore was referenced
within the function as $withscores. Changed argument name to $withscores
so they match.

Closes #941

Differential Revision: D934709
2013-08-20 09:04:53 -07:00
bsimmers e63912361a Miscellaneous cleanup
This is all stuff I did while working on guard relaxation
that isn't strictly related to guard relaxation:
- Stop using CheckType with Nullptr.
- Move a bunch of things from ir.cpp to extra-data.cpp and ssa-tmp.cpp.
- Turn DataTypeCategory into an enum class.
- Add folly::FormatValue specializations for JIT::Opcode,
  DataTypeCategory, and any objects with a toString method.
- Kill the Eval.JitCompareHHIR runtime option. Most of the code using
  it is already long gone.
- Add smart::flat_set.
- Clean up MInstrInfo constants, fixing a bug that missed some
  undefined local warnings.
- Assert that the type of IRExtraData subclasses passed to gen()
  matches what the opcode wants.
- Remove unused DontGuardLocal, DontBreakLocal, and DontBreakStack1
  from translator inputs.

Differential Revision: D926849
2013-08-20 09:04:52 -07:00
Mirek Klimos 3682f42d8a Removing unnecessary mapping of var ids on CreateCont.
Since D898769, all locals in generator bodies have the same ids
as in the corresponding 'create generator' methods, so the mapping
between these ids is no longer needed.

Differential Revision: D932354
2013-08-20 09:04:51 -07:00
Sean Cannella a8c26e832b Factor register shuffle algorithm into own module
Factor register shuffle algorithm into own module

Differential Revision: D932183
2013-08-20 09:04:51 -07:00
mwilliams 1cafbeb006 Remove some redundant bool parameters
No longer actually used

Differential Revision: D933388
2013-08-20 09:04:50 -07:00
Bert Maher c01103b732 Update NEWS for release
Updating the NEWS file for our next release.  These were some
highlights that I plucked from the commit log but I'm open to adding
or deleting some.

Differential Revision: D933280
2013-08-20 09:04:50 -07:00
Jordan DeLong 922a1fb454 Remove execute permission from ir.specification
Differential Revision: D932404
2013-08-19 10:15:20 -07:00
Jordan DeLong ffff9c7722 Remove doc/coding_guideline
Outdated and stuff.

Differential Revision: D932395
2013-08-19 10:15:20 -07:00
Jordan DeLong 81c8238c5b Delete doc/runtime.type_system
It's mostly describing hphpc.

Differential Revision: D932386
2013-08-19 10:15:19 -07:00
Mike Magruder 3fea3d93f7 Fix breakpoints on generators
Setting a breakpoint on a generator would work, but it would set it on the function which simply returns the continuation. That's not super-useful, and the intention is to set it on the beginning of the generator. Changed to do that. This change also gets the $continuation off of the function name when printing it at breakpoints.

Differential Revision: D931931
2013-08-19 10:15:19 -07:00
Andrew Gallagher de2fc5ca3b hphp: fix use of has_trivial_destructor
gcc-4.8 and 4.7 aren't consistent about this functions name, so use
boosts version instead (as per D923359).

Differential Revision: D925051
2013-08-19 10:15:19 -07:00
Herman Venter becb0e7784 Color output of = command. Update help. Implement "print r" to accompany "print v" and to provide a way of getting at old print behavior (if the old help text is to be believed).
The = command has recently been changed to use standard debugger serialization rather than to invoke a customizable function, or print_r otherwise. In the process a bug crept in that made the output not colored. This fixes that bug. It also updates the help text to make it clearer that = truncates text. While looking at that I noticed that the help text for the print command suggested that it's output is formatted with print_r. Fixed the text as well, but while I was at it introduced the "print r" flag to make it possible to invoke print_r, analogously to the already existing "print v" command. While adding test cases, I noticed that the truncation logic appears to be broken, so I fixed that as well.

Differential Revision: D931565
2013-08-19 10:15:18 -07:00
Sean Cannella 93e30adfaf SPL + filter extensions should report implemented
- Report that we implement SPL and filter extensions (needed for Drupal)

Closes #946

Differential Revision: D931374
2013-08-19 10:15:18 -07:00
Markus Staab efc12df155 add SplObserver and SplSubject interfaces
- add SplObserver and SplSubject interfaces

Closes #953
Closes #960

Differential Revision: D931324
2013-08-19 10:15:17 -07:00
Drew Paroski ed35cc6304 Update Iterable interface, add toArray() method
This diff adds a toArray() method to the Iterable interface, as well as
adding some other methods that were missing from the interface (map(),
filter(), etc). It also deprecates IterableTrait and KeyedIterableTrait,
introduces LazyIterable and LazyKeyedIterable as replacements, and adds
strict versions of the traits called StrictIterable and StrictKeyedIterable.
Finally, it deprecates the view() method (since I want to introduce a new
method named "view" that is semantically different) and introduces lazy().

Differential Revision: D923036
2013-08-19 10:15:17 -07:00
Jordan DeLong 0d56c48804 Always use lowercase names when tracking class aliases
I think the current situation is actually correct (we'll just
potentially have extra entries in the multimap), but this makes more
sense.

Differential Revision: D918976
2013-08-19 10:15:13 -07:00
Jordan DeLong 6a112e4866 Print duration of warmup requests
Differential Revision: D927403
2013-08-19 10:13:13 -07:00
mwilliams 26d097c39c Don't use low_malloc for preClass Funcs
They are rarely used at all, and never referenced from the
translation cache, so no need to put them in low memory.

Differential Revision: D930189
2013-08-19 10:13:13 -07:00
mwilliams ce47288fac Fix limit on low mem huge pages
The limit was still a bool, so we could only specify a limit
of 0 or 1. Since 1 was working fine, I've dropped the default from 200
to 32, and will test various values to see what works best.

Differential Revision: D929190
2013-08-19 10:13:12 -07:00
Mike Magruder 7f196d361e Add source location to async functions on the debugger async stack
Add source file and line to async functions on the debugger async stack. This information is only added for async functions which are not actually being executed. Those exist on the normal stack, and their location information is visible there. The location added for async functions which are not running is that of the yield which has caused the continuation to pause.

Differential Revision: D930103
2013-08-19 10:13:11 -07:00
Owen Yamauchi 7420c9a7ef Draw incision lines in translator-x64.h, delete some dead code
I deleted some dead code, but more importantly, organized the remaining
platform-specific declarations into thematic areas that I think can be
tackled (i.e. moved into explicitly platform-specific modules) as
self-contained units.

My determination of what's platform-specific was fairly loose. If it has
"emit" in the name it is for sure. Note that functionality that only
depends on the TCA type is *not* platform-specific: that was the point
of my diff to separate DataBlock and X64Assembler.

To be honest, I wasn't 100% rigorous on preserving access modifiers.
They're mostly the same, but some may have been changed in the shuffle.
I contend it doesn't matter that much since these members should be
moving to different modules soon, and also this class has so many
friends that most of its "private" members aren't really private as
such.

Because all the rearrangement makes the diff hard to read, here's the
list of declarations/definitions I found to be dead:

- emitDebugPrint, dumpStack, translatorAssert. Not used in the normal
  course of things, but it's possible people have been using them to
  debug; if so, I'll put them back.

- emitReRetransOpt (not dead, but since the definition was just a call
  to emitServiceReq and there's one callsite, I collapsed the chain)

- m_createdTime. It's declared in Translator (and only used there).

- emitIncRef*. These were moved to CodeGenerator earlier.

- toStringHelper. Unused.

- emitChainTo and emitIncCounter. No definition.

- {acquire,drop}WriteLease. We have a different abstraction for this.

- packServiceReqArg with one argument. It's not needed; that template is
  not recursive.

Differential Revision: D929657
2013-08-19 10:13:11 -07:00
Jordan DeLong aeac652f17 New StringData::append that uses reserve/escalate
Instead of having all the cases split out, this just goes
through the reserve/escalate paths.  I added geometric growth only to
the Smart mode in reserve (after the capacity check).  This makes it a
little easier to change how strings allocate (fewer allocation code
paths).

Differential Revision: D924293
2013-08-19 10:13:10 -07:00
Jordan DeLong 16a6ff7eeb Move increment_string() into StringData::inc()
After some changes I'm making locally, this will need to be
Mode::Malloc or Mode::Smart depending on the size of the new string,
which is easier to do from inside this same function. While at it,
let's make it reuse the buffer if it fits within the current
capacity().  (This allows small strings to stay small also; although
microbenchmarks on string increments are not particularly impressed by
it.)

Differential Revision: D920271
2013-08-19 10:13:02 -07:00
Jordan DeLong 83b4bf3acf Include the null terminator in string's capacity
I want to store the smart allocator size class here, so we
don't need to store it at the front of the smart malloced memory.  (We
can just tell smart_free how big it was, and possibly inline dropping
it on the appropriate free list.)  This isn't necessarily required for
that, but I decided to do it independently to make the changes easier
to think about.  (It's also maybe a marginal step toward not requiring
null terminators on the strings in general.)

Differential Revision: D917550
2013-08-19 09:01:33 -07:00
Bert Maher b789061519 Specialize SetNewElem when base is known to be array
Get rid of the switch-based dispatch on base type for
SetNewElem when we know that the base is an array.

Perflabs look like noise, except for one run that looks too awesome to
be believed:
https://our.intern.facebook.com/intern/perflab/experiment.php?diff_preview_id=2644370

Differential Revision: D927657
2013-08-19 09:01:33 -07:00
Aleksandar Ilic 0c3b36181b Hphp part for floats to thrift
Going together with D909976 and D913213.

Differential Revision: D921359
2013-08-19 09:01:32 -07:00
Sean Cannella d95ca0dc9a Add CodeGenHelpers[arch] for stateless helpers
Per discussion, create a stateless class for emitter utils that
can be implemented per-platform (to move code out of code-gen and
translator-x64)

Differential Revision: D927917
2013-08-15 15:19:36 -07:00
Bert Maher ecd61094e5 Add a stress-test mode that forces jitted execution
Sandcastle flib testing may be missing some coverage for the
JIT because tests that fail to get the write lease can execute in
interpreted mode.  Add a runtime option Eval.RequireWriteLease that
forces a thread to block on acquiring the write lease, so all test
code will be jitted.

Differential Revision: D921235
2013-08-15 15:19:35 -07:00
Jordan DeLong dc1f6c17eb static closures should inherit the late bound class
Mwilliams noticed an "obvious bug" in c_Closure::init, where
it always sets the late bound class to the context class in static
closures.  But it turns out thats what zend actually does.  This
behavior seems like a bug, so we're going to preserve the late bound
class.

Differential Revision: D814837
2013-08-15 15:19:35 -07:00
Edwin Smith 2f927eb29a Get rid of optional arguments in HphpArray helpers.
This just obscures what's going on and is making refactoring
more difficult.

Differential Revision: D927215
2013-08-15 15:19:34 -07:00
Owen Yamauchi 721a995726 Clean up punting to interpreter
There seems to be some strangeness left over from tx64 days. When the IR
took a slow exit trace, it would go through a "retranslate/interpret"
service request, which generated a stub translation that did nothing but
make an "interpret" service request.

I got rid of the BIND_JMP_INTERPRET and RETRANSLATE_INTERPRET service
requests, and replaced them with uses of the INTERPRET service request,
interping a single instruction.

Differential Revision: D927642
2013-08-15 15:19:34 -07:00
mwilliams b4d475fd9e Fix the build
I rebased past a rename of a private member
2013-08-15 15:19:33 -07:00
mwilliams 3072ea1e5b Don't let low_malloc hugify the entire tc
We carefully "enhugen()" portions of the tc. The problem is that low_malloc
maintains a high water mark, and every time it crosses into a new huge page
it marks everything up to the new high water mark huge. Since we allocate the
tc using sbrk, which allocates above the high water mark, the next time
low_malloc extends its arena, we mark the whole tc huge.

This adds some code to update the high watermark around the tc, and adds a runtime option to limit the number of huge pages used by low memory.

Differential Revision: D912684
2013-08-15 15:19:32 -07:00
Sean Cannella c1222d197a pull fixup outside of translator-x64
- pull fixup/sync code outside of translator-x64
- push codeblock related functions from asm-x64 down to codeblock to
  enable this

Differential Revision: D924632
2013-08-14 10:44:15 -07:00
Daniel Sloof 4a04f1ccba __get should be allowed for invalid properties
- Consistency with PHP, __get of an invalid property should
return an empty string instead of fatal

Closes #951

Differential Revision: D925220
2013-08-14 10:44:14 -07:00
Owen Yamauchi d6331ac3d9 Rename "no IR" stuff to reflect reality
This stuff all just punts to the interpreter, and there isn't such a
thing as a no-IR translation anymore, so let's clear this up.

I started thinking that maybe one of these steps isn't strictly
necessary. Currently, when we take a "slow" exit trace, we make a
RETRANSLATE_INTERPRET service request, which ends up creating a
"translation" that is nothing but an INTERPRET service request. This
feels like one more step than necessary; I think ideally we'd write out
an INTERPRET service request right in the exit-slow trace, but the
trouble right now is that at the point where we need to write it, we
don't know how many instructions should be interped.

Differential Revision: D925897
2013-08-14 10:44:14 -07:00
Mike Magruder 9b4501ce04 Add hhprof to news
The additon of hhprof, though under its own compilation flag, is worth mentioning

Differential Revision: D925547
2013-08-13 14:24:32 -07:00
Paul Bissonnette cfa4c3427c Adding OpAbs to codegen
fast absolute value computation and related optimizations

implemented Abs in interpreter

implemented Abs in codegen

added const folding for abs

updating docs

adding new test for abs()

Differential Revision: D896037
2013-08-13 14:24:32 -07:00
Eric Caruso 81f426be4b Translate CnsE and CnsU
These seem to be the last bytecode instructions left
to be translated that deal with namespaces and lookups, so we
might be able to get an OSS perf win out of them.

Differential Revision: D922132
2013-08-13 14:24:31 -07:00
Andrew Gallagher 4a9c32b507 hphp/util/service_data.cpp: add missing histogram #include
This file uses the ##getPercentileEstimate## templated function
without including the apprpriate header which defines it.  I'm
not entirely sure why building with gcc-4.8 triggers this issue
but it appears legit regardless.

Differential Revision: D923985
2013-08-13 14:24:31 -07:00
Andrew Gallagher b75d29d968 hphp: fix bug in JSON parser
gcc-4.8 exposed this issue via the end-of-array-subcript warnings.
The issue is that the top pointer is incremented before that check
to see if the push should happen.  If the push failed, the top
pinter is left incremented.

Differential Revision: D923932
2013-08-13 14:24:31 -07:00
Eric Caruso c58f9094eb Support for hhprof in client mode
A new runtime option will allow you to run in client
mode, but hang the execution thread until pprof collects the
heap dump or the HHProf thread timeout expires.

Differential Revision: D918754
2013-08-13 14:24:30 -07:00
Sean Cannella 8ec613f5b5 initialize thread locals before static constants
initialize thread locals first since static constant
initialzation assumes the memory manager is initialized

Differential Revision: D924209

Blame Revision: D915702
2013-08-13 14:24:30 -07:00
Andrew Gallagher 64654e47e0 hphp: remove unused local typedefs
gcc-4.8 complains about these.

Differential Revision: D923894
2013-08-13 14:24:29 -07:00
Drew Paroski 087e6e890c Remove more deprecated collections APIs
Differential Revision: D923014
2013-08-13 14:24:29 -07:00
Owen Yamauchi e1243c822d Fix build breakage
Post-rebase commit race.

Differential Revision: D924303
2013-08-13 14:24:28 -07:00
Drew Paroski da140be7e2 Miscellaneous cleanup
This diff gets rid of some mostly dead code and cuts down on the number
of uses of tvAsCVarRef().

Differential Revision: D923035
2013-08-13 14:24:28 -07:00
Paul Bissonnette 73553b7887 Remove native call Dbl -> Int conversion
use cvttsd2si to do conversion

Differential Revision: D905238
2013-08-13 14:24:27 -07:00
mwilliams 0ac0cf5564 Don't construct a new String/StringData for apc_unserialize
Every callsite of apc_unserialize constructed a String from a char*
and a length (involving at least one smart allocation, and a copy of the
data), passed it into apc_unserialize, which then extracted the char*
and length.

Just deal with the char*/length instead.

Differential Revision: D924015
2013-08-13 14:24:26 -07:00
Sara Golemon 35144c5398 Rewrite PHP function names to change _ to - in docComments
php.net manual URLs transform the function names
to use hyphens insteaf of underscores.  The autogenerated
docComments should reflect this.

Differential Revision: D922807
2013-08-13 14:24:26 -07:00
Joel Marcey ad3dcc4e7b Implement get_included_files()
PHPUnit self-test suite calls get_included_files(). Right now we return an empty array. That's not right. Implement correctly. Add and modify some tests as well.

Differential Revision: D922888
2013-08-13 14:24:25 -07:00
Owen Yamauchi de1b276ae7 Pull apart DataBlock and X64Assembler
This is one of the major spurious couplings I identified in my attempt
to get some code running in the ARM simulator. Currently, anything that
cares about the frontier of any of the code slabs is necessarily coupled to
X64Assembler, which doesn't make sense.

The solution in this diff is to remove DataBlock as a member of
X64Assembler. DataBlock is now in its own file, and TranslatorX64 has a
DataBlock member for each X64Assembler member. X64Assembler has a
pointer-to-DataBlock member. (I tried having it be a reference but that
doesn't work; in TranslatorX64::TranslatorX64() we have to construct
X64Assemblers without having their DataBlocks ready yet.)

I also discovered that the original reason for having DataBlock be a POD
type and having CodeBlock as a separate type seems to be gone, so I
consolidated the two classes and cleaned up some dead code.

There is more to be done here, which is to actually reap the benefits
and stop calling frontier() on X64Assemblers in translator-x64.cpp and
elsewhere. I'll do that in a separate diff because this state is a good
intermediate point.

Differential Revision: D918496
2013-08-13 14:24:25 -07:00
Mike Magruder 95e5b48cd9 Expose basic async stack in the debugger
Expose the async stack in the debugger. This is the stack of, say, generators driven from the ASIO extension. This is a modification to the where command. The new command type accounts for back compat between old servers/clients. I've added a shortcut, "wa", which is a bit faster to type.

I also modified the normal stack trace to not print bogus lines for functions with no file/line info.

Differential Revision: D920910
2013-08-13 14:24:24 -07:00
Jordan DeLong 8f8b12ae16 Some small changes for making valgrind clean when running hhvm with no args
We were reading uninitialized memory from tx64 member
variables and failing an assertion about the size of trampoline code.
(As far as I can tell, nothing really depends on the exact size of the
trampoline except for the guess about how many trampolines we can
fit.)

Differential Revision: D922916
2013-08-13 14:24:24 -07:00
Bert Maher 67aae18756 Test script support for debugging: write and compare printir logs
In trying to track down performance regressions I found it
was useful to generate printir:1 logs and compare them (Ed's idea).  I
figured others might find this useful so here's the test runner
support and script I used.

Differential Revision: D908406
2013-08-12 11:56:12 -07:00
Edwin Smith b62a3acde7 Rename files in runtime/server and facebook/runtime/server
Replace _ with -

Differential Revision: D922863
2013-08-12 11:56:05 -07:00
Drew Paroski eebf3bdced Make some collection APIs more lax about null and arrays
Looking at uses of the collection constructors, addAll, and setAll, I
noticed that it would be convenient if these methods tolerated null.
Also update Set::difference to support arrays.

Differential Revision: D923013
2013-08-12 11:33:04 -07:00
Jordan DeLong 8131f68221 Fix nemo errors for type aliases
:

Nemo is giving undefined class errors on type aliases.

Differential Revision: D918917
2013-08-12 11:33:04 -07:00
Drew Paroski 2a4f58d558 Fix HHVM to not allow collection literals in class constant definitions
HHVM was incorrectly allowing collections to be used in class constant
definitions. This diff fixes the bytecode emitter to throw a parse error
if a collection literal is used in a class constant definition.

Differential Revision: D922848
2013-08-12 11:33:03 -07:00
Sean Cannella 0084a8cc20 remove defunct segfault handler
- segfault handler never panned out and has been off for 1.5
years; cheaper to resurrect later from git than refactor to take it out
of tx64

Differential Revision: D922900
2013-08-12 11:33:03 -07:00
Sean Cannella bd7606c54f remove dead code from translator.h
remove dead functions/code from translator.h

Differential Revision: D922135
2013-08-12 11:33:02 -07:00
bsimmers 21a640569d Don't generate core files during test runs
When a diff that causes many tests to fail runs on contbuild,
it usually ends up timing out because the machine spends so much time
writing core files to disk. These files are almost never useful
anyway, so don't generate them.

Differential Revision: D922720
2013-08-12 11:33:02 -07:00
Benjamin Strahs 14245548e7 Fix missing openssl params
openssl_seal() and openssl_open() should both take an optional method parameter which allows you to select the symmetric cipher to use. This implementation is slightly different than Zend PHP, currently if you pass a cipher that requires an IV it segfaults in Zend, in this implementation it warns and returns false.

Differential Revision: D921384
2013-08-12 11:33:01 -07:00
Mirek Klimos ac56fafa55 Support for await on null expressions
The first implementation of async functions doesn't support
awaiting on expressions that are null. This adds support for this
in a way that the generator is not even suspended in these cases.

Differential Revision: D922499
2013-08-12 11:33:01 -07:00
Drew Paroski aed04c2799 Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5
The behavior of isset($x[$k]) and empty($x[$k]) where $x is a string has
changed in a recent version of PHP. This diff updates HHVM to match PHP
5.5's behavior. Note that HHVM still does not match Zend PHP 5.5 perfectly
in terms of warnings for these expressions; I've decided to put that off
into a separate diff.

This also brings HHVM up-to-date with respect to some edge cases for
automagically converting integer-like string keys to integer keys when
indexing into PHP arrays.

Differential Revision: D916630
2013-08-12 11:33:01 -07:00
Owen Yamauchi e42d796e26 Delete a bunch of dead code in TranslatorX64
I just went through the header and grepped for each member function
name, and it turns out a bunch of them were declared and not
implemented, or were implemented but not used.

This clarifies the picture of what assembler-coupled functionality
remains on TranslatorX64:

1. Func prologues and their transitive dependencies (including
unfortunate stuff like a duplicated implementation of emitIncRef).

2. One-time-use stub emitters.

3. Syncing VM registers.

This makes the project seems a little tamer. Func prologues are
definitely the biggest part of it.

Differential Revision: D921995
2013-08-12 11:33:00 -07:00
Mike Magruder e5f7c49775 Add a few more async tests for the debugger
Add a few more debugger async tests.

Differential Revision: D921498
2013-08-12 11:33:00 -07:00
Keith Adams cc70636040 Huge pages for server only, exclude targetcache by default.
Lots of scripts running in cli mode can quickly use up the huge page pool. Its better to not do that by default.

Even in server mode, it seems very suspicious to have large, thread-private segments of huge
pages. This should place heavy demands on the system's huge page resources,
and more worryingly, demand that scales up as threads go active.

Differential Revision: D885896
2013-08-12 11:32:59 -07:00
Daniel Sloof 9016abffaf use setCookie instead of manual header building
Instead of manually constructing a cookie, use the setCookie method
provided by Transport. This prevents the following kind of condition:

Imagine:

application runs setcookie with null params to delete a cookie.
application runs session_regenerate_id to get a new session id.
session_regenerate_id then constructs a new header through
m_responseHeaders.
Eventually, Transport will generate headers, but will always put
m_responseCookies after m_responseHeaders in the full header.

Uh oh! Now we have accidentally deleted a cookie due to incorrect header
order.

Closes #950

Differential Revision: D921467
2013-08-12 11:32:58 -07:00
Bert Maher b7034ab930 Allow guarding tracelets on ArrayKind
Enable guarding tracelets on ArrayKind when we can generate
better code for a specific kind.

Added specialized helpers for CGetM, FPassM, and IssetM of
vector-shaped arrays.  This eliminates an indirect call and allows the
entire array-access call stack to be inlined into the helper

Differential Revision: D873631
2013-08-12 11:32:58 -07:00
Mike Magruder 677b26fdf6 Remove a few extra vestiges of the debugger client api
Remove a few more bits left over from the client API, plus a little extra cleanup I noticed.

Differential Revision: D920393
2013-08-12 11:32:57 -07:00
Owen Yamauchi 876cbbb3eb Let $_SESSION be undefined until session start
In Zend, $_SESSION is undefined (i.e. reading it either directly or
through $GLOBALS results in an 'undefined' notice) until you call
session_start.

Right now we're not completely matching Zend on warnings, although we
get closer if you build with HHVM_MORE_WARNINGS (see
member-operations.h).

Differential Revision: D920224
2013-08-12 11:32:56 -07:00
mwilliams 67ec381c90 Fix incorrect UseUndeclaredVariable warnings
There were two bugs:

 - Methods from Systemlib traits that were imported into user
   code were still marked as system methods, so we didnt run
   type inference on them, so the parameter wasn't annotated correctly;
 - If we couldn't determine whether a function argument was by reference
   or not, we could end up marking *that* as being the thing that set
   the parameter. If later we figured out which function was being called,
   we marked it as *not* by reference, and then it looked like it was being
   used without being set.

With this diff, we set the system/user flag correctly when cloning methods,
and always mark the "declaration" of a parameter as the parameter itself.

Differential Revision: D920269
2013-08-09 10:30:43 -07:00
Sean Cannella fc59c6a00a Don't always call values() for array fcalls
We should only call values() when we absolutely have to (magic calls where the array is not a vector)

Differential Revision: D920504

Blame Revision: D917994
2013-08-09 10:30:43 -07:00
Sean Cannella 439d8d34fe folly::errnoStr is safer than Util::safe_strerror
- Eliminate Util::safe_strerror and use folly::errnoStr instead since the former is less safe as it doesn't preserve errno

Differential Revision: D920282
2013-08-09 10:30:42 -07:00
Sean Cannella 476bc58d6b don't hide errors from pthread_setspecific
pthread_setspecific can fail per the man page, we should be
checking the return value

Differential Revision: D919949
2013-08-09 10:30:42 -07:00
Jordan DeLong c98ebd8156 Fix a bug in StringData::escalate
Needed to delist and decref the shared variant.

Differential Revision: D920482
2013-08-09 10:30:41 -07:00
Sean Cannella 48babc3898 StringData allocator must be initialized
- For slow TLS ThreadLocalSingletons must be initialized

Differential Revision: D919977

Blame Revision: D907959
2013-08-09 10:30:41 -07:00
Jordan DeLong 6a500a5237 Fix static closures *not* to do LSB in the JIT
:

Apparently this is intentional bug compatibility with zend.

Differential Revision: D919411
2013-08-09 10:30:40 -07:00
Mike Magruder 29669189dd Enable ctrl-c during eval
Enable the support for signal polling during eval in the debugger.

Differential Revision: D910661
2013-08-09 10:30:40 -07:00
Mike Magruder d785895036 Add function to get dependency stack on WaitableWaitHandle
Add a function to get the wait handle dependency stack to the native implementation of WaitableWaitHandle. This will be used by debuggers and profilers to get the stack of dependencies for generators driven from ASIO.

Differential Revision: D919486
2013-08-09 10:30:39 -07:00
Vaishaal Shankar d5e6b2b96e unbroke type profiler
Fixed profiling implementation, moved soem of profiling ir opcode params into extra data

Differential Revision: D913367
2013-08-09 10:30:33 -07:00
Guilherme Ottoni 046c176b71 Avoid division by zero when aprof isn't allocated
That's it.

Differential Revision: D919880
2013-08-08 09:29:44 -07:00
Sara Golemon c03b010a7e Move MySQL config settings into ext_mysql
Organization and de-monolithification.

Differential Revision: D918185
2013-08-08 09:29:43 -07:00
Jordan DeLong 8eae97545a Smaller string mode tests, don't overlap mode with capacity
Looking at the generated code for various StringData mode
dispatch cases, there were 64-bit immediates being put in registers
often to test the format value.  We also did masks on the capacity
just to see that the string was small.  This switches to just load the
byte that actually contains the mode, and use a 32-bit integer for
capacity (the largest string size fits in this).  Small checks only
need to compare that byte with zero.

Differential Revision: D914034
2013-08-08 09:29:43 -07:00
Jordan DeLong 88d5a1d8b7 Fix a capacity under-estimate in StringData::escalate
This looks like it should be using cap.  (The allocation size
is cap + 1.)

Differential Revision: D917389
2013-08-08 09:29:42 -07:00
Jordan DeLong c1974eaf60 Fix a bug for typedefs to mixed when parameters are an object
Oversight in the case where it was an object.
(checkTypedefNonObj handled it properly.)

Differential Revision: D917712
2013-08-08 09:29:42 -07:00
Edwin Smith 59ac1d67e5 Rename files in hhvm
Differential Revision: D914023
2013-08-08 09:29:35 -07:00
Sean Cannella 0a3901d4cf Calculate dynamic invariant constants per process
- Cache and store invariant dynamic constants and set per
session instead of making more expensive calls

Differential Revision: D915702
2013-08-08 09:11:25 -07:00
Daniel Sloof 1ecc70eeff Fix arguments with __call and call_user_func_array
- Fix call_user_func_array to be Zend compliant, see new test
case

Closes #939

Differential Revision: D917994
2013-08-08 09:11:24 -07:00
Edwin Smith 860d410367 Streamline NewTuple and NewArray helpers
Rearrange the code so when we allocate an array from JIT code,
we call one helper where most of the code is inline.

Differential Revision: D917956
2013-08-08 09:11:24 -07:00
Scott Renfro 9a4fdfc892 Fix TLS CURLOPT when SSL_OP_NO_TLSv1_1 not defined
This was busted in two ways:
1. SSL_OP_NO_TLSv1_1 wasn't guarded by an ifdef in one location
2. SSL_OP_NO_TLSv1_1 was used instead of SSL_OP_NO_TLSv1_2
in one location.

Differential Revision: D917255
2013-08-07 09:55:23 -07:00
Jordan DeLong 258b71a5d5 Rename string_data-inl.h to string-data-inl.h
Differential Revision: D917064
2013-08-07 09:55:23 -07:00
Edwin Smith 783301a6f8 Rewrite findBody and findForInsertBody as functions taking lambdas.
The way we use these macros is exactly what lambdas are for, so
give it a try.

Differential Revision: D916121
2013-08-07 09:55:22 -07:00
Owen Yamauchi edfb74a80b Add a NativeCall pseudo-opcode to VIXL
We'll need the ability to call native functions (i.e. written in C++)
out of the simulated-ARM translation cache. VIXL already has support for
pseudo-opcodes that the simulator understands and treats specially (it's
a trap instruction with payload in some unallocated bits), so I added a
new one that will read a function address out of an inter-procedural
scratch register and arguments out of the usual argument registers, call
the native function, smash simulated caller-saved registers, and put the
return value in the simulated return value register.

Differential Revision: D916164
2013-08-07 09:55:21 -07:00
Edwin Smith de4259e8ae Rename rest of files in runtime/base
Differential Revision: D913884
2013-08-06 09:23:21 -07:00
Drew Paroski bf0846c516 Improve sort comparator warning message
Some developers were a little confused by the warning message printed when
a sort comparator returns a boolean. This updates the messages to be more
clear and more explicit.

Differential Revision: D909645
2013-08-06 09:23:19 -07:00
Aurelien Fredouelle 9e32fdc3fe Removed the Locale implementation
Symfony relies on class_exist('Locale') to check if the intl extension is
enabled. By removing this Locale class, we let Symfony use the stubs they
provide.

Differential Revision: D908679
2013-08-06 09:23:19 -07:00
Aurelien Fredouelle 663903371d Implemented highlight_file and highlight_string
Differential Revision: D913227
2013-08-06 09:23:18 -07:00
Paul Bissonnette 34524b59a1 Fixing issue in instructionsAreSinkable
the function wasn't actually checking if all the instructions were safe to sink

Differential Revision: D915210
2013-08-06 09:23:18 -07:00
Drew Paroski 4412f99b27 Remove unused runtime option "StrictCollections"
This runtime option was removed from all config files a while ago and is
no longer used. Let's get rid of it.

Differential Revision: D909886
2013-08-06 09:23:17 -07:00
Sara Golemon b0ea37ccfd Implement Redis session module
Translates session events into Redis commands

Differential Revision: D872896
2013-08-06 09:23:17 -07:00
mwilliams ca4f0e09ad Allow separate timeout for postsend
Add a new runtime option: Server.PspTimeoutSeconds.
If its zero, postsend gets the same timeout that the request was running under. If its less than zero, postsend will get min(time remaining for main thread, -Server.PspTimeoutSeconds), and if its greater than zero, it will get exactly Server.PspTimeoutSeconds.

In addition, fixed cli mode to respect Server.RequestTimeoutSeconds.

Differential Revision: D914478
2013-08-06 09:23:16 -07:00
Jordan DeLong 1abc7a911d Something already fixed these ones
Differential Revision: D910062
2013-08-06 09:23:16 -07:00
Jordan DeLong 398418ba56 Remove another TypedValue -> boolean helper
Differential Revision: D910135
2013-08-06 09:23:16 -07:00
Jordan DeLong b5c0ecb26f Fix a SEGV for zend's bug54265.phpt
Differential Revision: D910055
2013-08-06 09:23:15 -07:00
Jordan DeLong ae30d7480c Fix a few SEGVs relating to cyclic data with SETOP_BODY
Test cases inspired by zend test bug35239.phpt.  I think
there are other cases where SETOP_BODY should be SETOP_BODY_CELL, but
I looked at them mainly to see if they would crash, not if they were
optimal.  (Except I changed SetOpL which seemed to be doing tvToCell
twice for no reason.)

Differential Revision: D910025
2013-08-06 09:23:15 -07:00
Jordan DeLong 30e85006aa Fix SEGVs found by zend test bug35239.phpt
We dereferenced some potentially-freed memory only in order
to return something no one needed.  Remove the return value from
ObjectData::setProp.

Differential Revision: D909967
2013-08-06 09:23:15 -07:00
Sara Golemon e389ed81dd Implement a general purpose Systemlib SessionModule wrapper
To implement a session module in PHP, add a small C++ class
in runtime/ext/ext_session.cpp

  static class MySesionModule : public SystemlibSessionModule {
   public:
    MySessionModule() : SystemlibSessionModule('my', 'MySessionModuleImpl') {}
  } s_my_session_module;

Where 'my' is the name of the session handler (as known by the ini setting)
'MySessionModuleImpl' is the Systemlib PHP class implementing SessionHandlerInterface

Differential Revision: D872889
2013-08-06 09:23:14 -07:00
Vanilla Hsu 328607b4a8 use f_php_uname() to replace hardcoded PHP_OS
- PHP_OS should return the real OS instead of Linux

Closes #933

Differential Revision: D914263
2013-08-06 09:23:14 -07:00
Guilherme Ottoni 19c863bf42 Name next release
And also switch over to unambiguous date format.

Differential Revision: D914499
2013-08-06 09:23:14 -07:00
Chip Turner a0cdd8300e (retry) Fix bug in mysql_next_result's return value that confused "done" with "error"
The MySQL documention states that mysql_next_result's return
values are:

0	Successful and there are more results
-1	Successful and there are no more results
>0	An error occurred

However, we were casting it to a bool, meaning errors and "all done"
were mixed into the same result.

This diff brings back the full error range.

This diff requires D912547, which fixes unit tests to accept both the
new and old return value types.

Differential Revision: D912553
2013-08-06 09:23:13 -07:00
Jordan DeLong 0c2dc63438 Disable apparently broken dead store removal in hphpc
Hphp optimizes code like ($k += foo) into $k + $foo even if
$k is referenced again later in the function.

Differential Revision: D914064
2013-08-06 09:23:13 -07:00
Bert Maher b4fe8dc9fb Streamline a bit of code in AssignValHelper
The old code was constructing a Variant on the stack just to
decref it via the destructor.  Just call the decref directly and avoid
a few memory operations.

Differential Revision: D913228
2013-08-06 09:23:12 -07:00
Edwin Smith 251ebf9685 Rename files in runtime/base, part 7
Differential Revision: D913883
2013-08-05 14:42:18 -07:00
Edwin Smith 55494c2443 Rename files in runtime/base, part 6
Differential Revision: D913699
2013-08-05 14:42:17 -07:00
Edwin Smith 03fec81145 SetStr and AddStr methods on a Vector do the same thing.
Since vectors are guaranteed not to have strings, set and
add are identical.

Differential Revision: D914016
2013-08-05 14:42:17 -07:00
Edwin Smith 355a49c38f Rename files in runtim/base, part 5
Differential Revision: D913077
2013-08-05 14:42:17 -07:00
Stephen Chen e986ae1387 make the fb303 server work with port takeover
Make the fb303 server work with port takeover. We need to give it the same
treatment as admin server / satellite servers. Sorry I missed this part before
and being lame.

Differential Revision: D897344
2013-08-05 14:42:17 -07:00
Jordan DeLong c608b6cbd1 Some const-correctness fixes for collections
Gets rid of a TODO from when I implemented cellEqual.

Differential Revision: D911145
2013-08-05 14:42:16 -07:00
Jordan DeLong d9cb5f5d9a Make StringData constructor/destructor private
Everything has to go through StringData::Make or
StringData::MakeMalloced now.

Differential Revision: D909781
2013-08-05 14:42:16 -07:00
Jordan DeLong 871ba9aafd Optimize StringData::release a little
Strings are usually small, and failing that, usually smart
allocated.  Also, release() doesn't need to check for a null pointer
now that it's not controlled by the DELETE macro.  This just inlines
the small path and gets rid of the null check for now.

Differential Revision: D907960
2013-08-05 14:42:16 -07:00
Jordan DeLong 5cfd77fd49 Don't use NEW and DELETE macros for StringData
This is a step toward having StringData take control over how
it talks to the smart allocator based on its constructor parameters.
For now nothing is done to prevent allocation without going through
the new proxy function, but the nested allocator type is renamed to
prevent adding new uses of NEW or DELETE.

Differential Revision: D907959
2013-08-05 14:42:16 -07:00
Paul Tarjan f8359e6b7f kill HasDocComment
Why does this exist? Can't we just rely on the key being there? I've seen tons of functions with this flag and no comment...

Differential Revision: D909139
2013-08-05 14:42:16 -07:00
Mirek Klimos 88f2569735 Basic support for async functions using continuations.
Adding basic support for async functions using continuations, which should be semantically fully equivalent to yield wait_for() etc.

Differential Revision: D911571
2013-08-05 14:42:15 -07:00
Mirek Klimos 2add534031 Moving type inference of generator calls to FunctionCall expr.
Let's move the type inference for generators from function scope to
function call, so that the original infered type is kept in func scope
and can be used later (will be useful especially for async functions
lates).

Differential Revision: D913970
2013-08-05 14:42:15 -07:00
Mirek Klimos 8801eff71b Parsing member modifiers refactorization.
Currently, normal functions are not allowed to have modifiers and
closures can be marked only with 'static' keyword, which needs special
treatment in the parser. Let's change it so that it's parsed in the same
way as method modifiers. This will help us later when introducing 'async'
modifier for both functions and closures.

Differential Revision: D913903
2013-08-05 14:42:14 -07:00
Edwin Smith 45ac3b1d99 Add a dedicated VectorInit helper for vector-shaped arrays.
This replaces ArrayInit's vectorInit constructor.  When we
know we're making a vector-shaped array, there's no need to
internally use the general array api; ArrayInit provides the
api, internally we do what's fastest.

Differential Revision: D903252
2013-08-05 14:42:14 -07:00
Edwin Smith 838df51012 Refactor HphpArray internal helpers
Create and use set[Val,Ref] and init[Val,Ref,Lval,WithRef]
helpers, to factor out tricky, repetitive code.  These will
get even more airplay as we add more shapes.

This diff also fixes a bug in PopVec(): we need to erase the
value (and update the array's fields) completely before
calling decref on the value.  Getting this wrong can mess
things up with array<->object cycles because calling decref
can reenter another array method, which would see the fields
in an invalid state.

Differential Revision: D905136
2013-08-05 14:42:14 -07:00
Herman Venter 205ec4913f Use unit->isInterpretOnly() inside JIT, not VM, so that debugger eval can invoke JITted code
The units that result from Eval code injected by the debugger should always be interpreted because they are used once only, however, any code invoked by these units should be JITtable. This diff moves the test for disabling the JIT from VMExecutionContext to Translator::isSrcKeyInB. It also fixes a cut&paste error that inverted the logic for Unit::isInterpretOnly().

Differential Revision: D913723

Blame Revision: D904873
2013-08-05 14:42:14 -07:00
Joel Marcey 3807e939bd Fuller implementation of get_defined_constants() to support categorization
The PHPUnit test suite calls get_defined_constants(true), for categorization. We threw. Now we don't. Now we actually do something sort of correct, but not fully correct. We have a "user" and "core" constant categorization. Function cleanup and consolidation. That's good. But Zend categorizes even more into extensions. This is a first step. And two (2) tests now move from zend/bad to zend/good.

Differential Revision: D909942
2013-08-05 14:42:14 -07:00
Herman Venter e5983c0e98 Handle case where a break point is hit followed by a continue that returns to the break point without intermediate interpreted instructions.
Breakpoints correspond to source lines, not byte code operations, so more than one operation may correspond to a break point. Each operation checks for breakpoints, so breakpoints are disabled when encountered, otherwise commands such as continue and next would get stuck on a line until all the byte code operation for a line have been carried out. Such break points are re-enabled as soon as a byte code for another line is executed. This does not work if no other byte codes are carried out (i.e. if JITted code runs) until control loops back to the disabled break point. Consequently the disable logic now keeps track of the offset of the byte that first triggered disablement. If the break point is still disabled by the time control comes back to that byte code, the break point is temporarily enabled.

Differential Revision: D909092
2013-08-05 14:42:13 -07:00
Eric Caruso 050f5d56b7 Record block postconditions and use them to prune CFG arcs
The region selector will now refrain from choosing paths
through the translation CFG where the postconditions of the
sequence of blocks chosen up until that point have no chance of
passing guards.

Differential Revision: D907313
2013-08-05 14:42:13 -07:00
Mike Magruder e85a361d34 Remove the debugger client API
The debugger's API mode added a lot of extra complexity to the debugger client for minimal value. It also had a bunch of bugs, and unnecessarily tied alternate debugger clients to the command line client implementation. Deleting it.

Differential Revision: D912729
2013-08-05 14:42:13 -07:00
Scott Renfro 4dfcee9335 Add CURLOPTs to override TLS options from PHP
This will let us use TLSv1.2 or specialized cipher suites on internal
requests while avoiding breaking Microsoft and other partners on
external requests.

Differential Revision: D912541
2013-08-05 14:42:13 -07:00
Scott Renfro f0d652d9ba Add RuntimeOption::TLSClientCipherSpec
We need a way to configure which cipher suites are used when
we are acting as a TLS client using Curl. This option accepts
the standard OpenSSL cipher suite spec, which will allow us
to turn off some cipher suites.

Upgrading OpenSSL without this will cause us to send too many
cipher suites in the client hello, crashing Bing's F5 load
balancers.

Differential Revision: D911814
2013-08-05 14:42:13 -07:00
Edwin Smith 98fdfc266b Rename files in runtime/base, part 4
type_* and tv_*

Differential Revision: D912522
2013-08-05 14:42:13 -07:00
Owen Yamauchi c75bae5af3 Delete atomic_inc
This was a little weird: I deleted the definition first, and everything
compiled because all the usages now are behind ifdefs that we don't test
regularly. In the interest of not ruffling feathers over deleting this
code, I just went ahead and made the changes. I would like to suggest
deleting all this stuff, especially the GOOGLE_HEAP_PROFILER stuff, for
which the make target has been deleted for a long time.

Again, all the usage sites are using the default memory order specifier,
which is memory_order_seq_cst. They could stand to be relaxed, but I
didn't find it worthwhile.

I'd also like to replace atomic_acquire_load and atomic_release_store
with portable and correct alternatives. We really just shouldn't be
rolling our own atomic primitives.

Differential Revision: D909903
2013-08-05 14:42:13 -07:00
Owen Yamauchi aba544ba90 Fix some macro name collisions in vixl
As I try to include vixl from the jit backend, these macros are clashing
with ours. Codemod them all to use our macros from util/assertions.h.

Differential Revision: D912687
2013-08-05 14:42:12 -07:00
Mike Magruder 6cdbb86af5 Delete CmdUser
One more step on the road to deleting the hphpd client API.

Differential Revision: D908926
2013-08-05 14:42:12 -07:00
Edwin Smith 7e528ecb84 Coerce uninit->null in HphpArray 'add' functions.
The vector shape code calls addVal() in more ways than
before, so there might be client code seeing uninit when
they used to see null before.

Differential Revision: D912686

Blame Revision: D879416
2013-08-05 14:42:12 -07:00
Sara Golemon 3e85221156 Add literal and pattern exclude option to test/run
Run a whole suite except for specified tests

Differential Revision: D912868
2013-08-05 14:42:12 -07:00
Edwin Smith 4cb3db473e Rename files in runtime/base, part 3
renamed runtime/base/*file*

Differential Revision: D912500
2013-08-05 14:42:12 -07:00
Edwin Smith 0b6b336922 Rename _ to - in runtime/base, part 2
Differential Revision: D912410
2013-08-05 14:42:11 -07:00
Sara Golemon f27622b4e1 Merge pull request #932 from danslo/libevent
register_libevent_server has to be prefixed on OSX.
2013-08-05 10:22:17 -07:00
Daniel Sloof 3ebe6c3414 register_libevent_server has to be prefixed on OSX. 2013-08-02 23:52:46 +02:00
Mike Magruder ea77c958ba Fix segfault in CmdNext at request start
Request Start has no activation record on the stack, but Next is quite valid and should still work. Modified to tollerate the lack of act rec.

Differential Revision: D908499
2013-08-02 14:22:12 -07:00
Edwin Smith 53df4a7c53 Fix a few uninit_null() sites should be regular null.
I found the one in ArrayUtil::Map while debugging the array code,
and the others are just from inspection.

Differential Revision: D906683
2013-08-02 14:22:11 -07:00
Edwin Smith 4aba0c8a08 Rename runtime/base/zend_* to zend-
Incrementally renaming foo_bar.* to foo-bar.*.  runtime/vm
is nearly done, getting started on runtime/base.  This does
a dozen or so files, will do more in separate diffs.

Differential Revision: D910489
2013-08-02 14:22:10 -07:00
mwilliams 7eb3f8fb4e Revert "Fix bug in mysql_next_result's return value that confused "done" with "error""
Differential Revision: D911994
2013-08-02 14:22:05 -07:00
mwilliams 27bb515314 Revert "Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5"
Differential Revision: D911544
2013-08-02 14:22:00 -07:00
Guilherme Ottoni 613ac4e7d3 Only enable PGO for hot functions in server mode
This seems to get JitRegionSelector=hottrace working in perflab.  I
still left all functions being profiled in non-server mode, so that we
can run tests and measure benchmarks.

Differential Revision: D908942
2013-08-02 14:21:59 -07:00
mwilliams 0e5e165224 Unrevert "Raise a recoverable error when Obj->Str conversion fails""
Differential Revision: D906304
2013-08-02 14:21:52 -07:00
Paul Tarjan 8b78248845 fix recursive server rewriting
If a URL doesn't exist and is going to 404, we set `m_originalURL` to the 404 handler, but don't update the boolean to the fact that it hasn't been rewritten yet.

Differential Revision: D911365
2013-08-02 12:58:00 -07:00
Mike Magruder 5e6cb40a28 Fix debugger protocol break
I slipped and locked the wrong mutex on the signal polling thread with a recent diff, allowing two threads to send to the client at the same time. Fix that, and remove the other similar lock which was superflous.

Differential Revision: D911162

Blame Revision: D897309
2013-08-02 12:57:58 -07:00
Bert Maher 99685ccdd1 Fast path for intermediate Elem ops when the base is an array
We can call faster helpers for intermediate m-ops when we
know the base is an array, saving us a switch-table dispatch in
Elem().  In practice this only applies to the first intermediate m-op,
because subsequent ops won't have known type.  At least for now.

Differential Revision: D903464
2013-08-02 12:57:57 -07:00
Owen Yamauchi b2db98d0c6 Delete GOOGLE_HEAP_PROFILER and transitive dependencies
As far as I know we haven't used this in a while, we don't build with it
regularly, and in fact the Makefile with the commands to build with it
has been deleted since right around the fbcode transition.

It turned out to be the only thing holding LeakDetectable in the
codebase, as well as a runtime option.

We should just use jemalloc's profiling now if we need heap profiling,
and maybe a bit of valgrind too.

Differential Revision: D910760
2013-08-02 12:57:31 -07:00
Aurelien Fredouelle e4fc177c16 Cache the current SessionModule when calling set_save_handler
When the user provides a custom SessionHandler via the function
session_set_save_handler, we need to cache the current SessionModule,
as it will be the one called by the user's SessionHandler.
Also added a check to make sure we don't call set_save_handler when
the current handler is already a user-defined one.

Differential Revision: D910794
2013-08-02 12:55:38 -07:00
Vaishaal Shankar 76b6cdee6a Type profiling implementation
I've implemented type profiling in the jit, I added an ir opcode that will log one parameter or return value of a function. I emit that opcode during an FCall, and during a RetC. Each Func object maintains an array of atomic hashmaps (for each parameter), and the atomic hashmaps are basically just counters for each type at runtime.

Differential Revision: D890038
2013-08-02 11:10:32 -07:00
Herman Venter 52503f5ea8 Do not cache units containing eval code created by debugger
A number of debugger commands end up doing an eval inside the VM. These eval's are ad-hoc and are performed in human time scales. There is no need to cache them. Consequently, call compile_string directly, rather than call it via compileEvalString (which does caching). Also make sure that the result of compile_string is always interpreted so that no JIT caching happens.

In principle, caching ought not to matter, but another bug is causing the JIT to fail an assertion if a cached eval string is recompiled in a context where variables that were bound are no longer bound.

Differential Revision: D904873
2013-08-01 18:27:25 -07:00
Mike Magruder 125939e6e6 Make ctrl-c in hphpd just a little less annoying
Modify ctrl-c handling in the debugger to give up and kill the client after three presses, rather than 10 seconds. Change the wording as ctrl-c is pressed to hopefully be more clear.

Differential Revision: D908728
2013-08-01 18:27:24 -07:00
Owen Yamauchi 9a135bdf6f Delete atomic_dec
Resurrecting this thing I did ages ago. It's mostly similar and
mechanical, except for the stuff in SharedVariant. I got rid of the
anonymous union and struct because that doesn't play nice with the
std::atomic constructor. The static asserts below should give us all the
same guarantees we had before.

Note that I'm freely using operator++ and operator--, which use the
sequentially-consistent memory order for their underlying ops. However,
I've looked on both x64 and ARMv8, and these ops in particular do the
exact same thing regardless of what memory order specifier you pass.

Differential Revision: D909344
2013-08-01 16:07:33 -07:00
Sean Cannella 4beebed3b2 fix license script after zend folder flattening
- don't add zend license to all files in runtime/base
- exclude vixl from license path

Differential Revision: D910454
2013-08-01 13:31:51 -07:00
Herman Venter 5d012ac1f0 Log unexpected exceptions that occur when carrying out debugger commands
When we hit a breakpoint while processing a CmdEval, we print the line that we hit the breakpoint (which we see), then we send a nested CmdList to the proxy to get the source file. There is no handling of exceptions in CmdList::onServer(), so any exception would bubble out of the server-side command execution. Normally an exception at such a point would cause the proxy to shutdown, but there is a ton of quite general error handling around eval, and it looks like it will swallow the exception and merrily attempt to complete the processing of outstanding CmdEval, thus sending a CmdEval to the client and generating the output we see.

This diff adjusts the code in the catch(...) block in DebuggerProxy::processInterrupt() to log instead of trace, and introduce a similar catch of Exception to dump what we can about the exception. That would give us more data to start to track this very transient problem down.

Differential Revision: D908369
2013-08-01 13:29:41 -07:00
Drew Paroski b947636a57 Fix isset($string[$k]) and empty($string[$k]) to match PHP 5.5
The behavior of isset($x[$k]) and empty($x[$k]) where $x is a string has
changed in a recent version of PHP. This diff updates HHVM to match PHP
5.5's behavior. Note that HHVM still does not match Zend PHP 5.5 perfectly
in terms of warnings for these expressions; I've decided to put that off
into a separate diff.

This also brings HHVM up-to-date with respect to some edge cases for
automagically converting integer-like string keys to integer keys when
indexing into PHP arrays.

Closes #844

https://github.com/facebook/hiphop-php/issues/844

Differential Revision: D905081
2013-08-01 13:29:40 -07:00
Bert Maher 7fc005b6f4 Expose specialized class guards to IR
Guards on object class (and, eventually, array kind) need to
load the ObjectData to get at the class.  This is the same operation
as a LdLoc, so if we use that IR instruction to implement the class
guard we can CSE the LdLoc where the object is actually used.

Differential Revision: D906267
2013-08-01 13:29:40 -07:00
Jordan DeLong e51a04eaae Convert LdGblAddrDef to use native-calls
Differential Revision: D903863
2013-08-01 13:29:39 -07:00
Jordan DeLong d618384e11 Cut down some on cgCallHelper overloading
Factor destType and the destination register/ssa situation
into one parameter instead of a family of up to 3.  Remove the TCA
overload (casting to TCA at every callsite is no more convenient than
making a CppCall at every callsite).

Differential Revision: D903862
2013-08-01 13:29:39 -07:00
Jordan DeLong 3573e13e54 Directly call several conversion functions from the TC
Skip little wrapper functions for few non-virtual member
functions, and add support for immediates to native-calls so we can
call StringData::toInt64 directly with the defaulted argument.

Differential Revision: D903835
2013-08-01 13:29:39 -07:00
Jordan DeLong b8310bab3b Store CppCall objects instead of TCAs from native-calls.cpp
I did this because I thought we couldn't call member
functions the way things are, but apparently the direct interface
check stuff was already doing it, just with appropriate casting
through Util::getMethodPtr.  This still seems nice though, so I'm
putting it up (less casting in the actual table...).

Differential Revision: D903831
2013-08-01 13:29:34 -07:00
Jordan DeLong ab3118df75 Remove now-redundant convCellToBoolHelper
It's just cellToBool.

Differential Revision: D903823
2013-08-01 11:57:47 -07:00
Chip Turner f43ba24414 Fix bug in mysql_next_result's return value that confused "done" with "error"
The MySQL documention states that mysql_next_result's return
values are:

0	Successful and there are more results
-1	Successful and there are no more results
>0	An error occurred

However, we were casting it to a bool, meaning errors and "all done"
were mixed into the same result.

This diff brings back the full error range.

Differential Revision: D907075
2013-08-01 11:57:47 -07:00
bsimmers 34e7b6b7c1 Fix region translator tests
A few of the diffs I rebased onto each other and pushed last
night didn't play nice with each other.

Differential Revision: D908416
2013-08-01 11:57:46 -07:00
Jordan DeLong 5e3ae9637f (Re)move a few more unused/out-of-place functions on StringData
StringData::getPrecomputedHash was unused.  The
isValidVariableName thing was a thin wrapper on a zend function that
is hardly used, and it shouldn't be a member function anyway.  The
convert_double_helper and convert_integer_helper also shouldn't be
member functions, and the former duplicated buildStringData(double)
too much for me so I removed it.

Differential Revision: D903915
2013-08-01 11:13:19 -07:00
Jordan DeLong d50b200caa Remove buildStringData(litstr)
Barely used.

Differential Revision: D903895
2013-08-01 11:13:19 -07:00
Jordan DeLong 5662c99c30 Some String-related micro cleanups, comments and unneeded function removal
String::set was one of two users of StringData::Escalate.
Leaving the remaining use alone for now until I know where it'll go.
Reordered some members and updated some comments.

Differential Revision: D903882
2013-08-01 11:13:19 -07:00
Jordan DeLong 719a46546f StringData::m_count doesn't need to be protected
Also move private helpers ahead of private data.

Differential Revision: D903874
2013-08-01 11:13:18 -07:00
Jordan DeLong 3c29f15450 Remove comment referring to closed task
Differential Revision: D903869
2013-08-01 11:13:18 -07:00
Sara Golemon 132241f5e5 Implement session_status()
And export PHP_SESSION_(NONE|DISABLED|ACTIVE) constants.

Differential Revision: D908419
2013-07-31 12:25:21 -07:00
Guilherme Ottoni 2a91b4f540 Don't pass type prediction after Div interpOne
This is generating CheckTypes even when the value is not used.

Differential Revision: D907386
2013-07-31 12:25:21 -07:00
huzhiguang 3bbb2d22e7 fix compile_string memory leak
Fix memory leak in compile_string

Closes #879
Closes #917

Differential Revision: D908222
2013-07-31 12:25:20 -07:00
bsimmers e63215987c '_' -> '-' in runtime/vm/*
To be consistent with runtime/vm/jit

Differential Revision: D906425
2013-07-31 12:25:20 -07:00
Sean Cannella ba05c1d0d6 stats URL/response code filters did the opposite
- Per Github, URL/code filters, if specified, actually filtered
out only the code/URL as opposed to restricting it to the URL/code of
interest

Closes #912

Differential Revision: D906156
2013-07-31 12:25:19 -07:00
James Miller 64b1ffe624 gcc 4.8 compilation fixes
gcc 4.8 fixes from Github

Closes #889

Differential Revision: D900456
2013-07-31 08:06:33 -07:00
Eric Caruso 8f0d01d7bd Add runtime options for pprof server port and threads
As stated on the hhprof wiki page, this allows some
extra configuration.

Differential Revision: D899538
2013-07-31 08:06:32 -07:00
Eric Caruso a37f11eb4f Add cancellation endpoint to pprof server
You can now cancel profiling by sending a GET request to
/hhprof/stop. I also added an extra thread to the server so you
can un-hose yourself if one thread is waiting on a profile, but
it's still possible to deadlock if multiple clients try to get
the profile.

Differential Revision: D897271
2013-07-31 08:06:32 -07:00
Eric Caruso 584b8abf02 Add NextURL and Global profile request modes to pprof server
/hhprof/start will now also take parameters:
type = "next" (default) or "global"; "next" will profile the
next request or the next request to a particular URL if the url
parameter is present, and global will profile all requests until
stopped (but waits for at least one)
url = <some url>; if present and the request type is "next", then
it will get a profile for the next request to the given URL.

Differential Revision: D896989
2013-07-31 08:06:32 -07:00
Eric Caruso b0a8dde8de Add pprof server
hhvm will now respond to pprof requests. Start up a
server, curl /hhprof/start to put in a request to profile, then
fire pprof at /pprof/heap to get a heap profile.

Differential Revision: D896906
2013-07-31 08:06:32 -07:00
bsimmers d28cf653e9 interpOne bugfixes for vector instructions
This diff fixes a bunch of issues with interpOne of vector
instructions that only show up when the rest of the trace is
translated normally. I ran into them trying to perflab turning off the
vector translator.

Differential Revision: D901267
2013-07-31 08:06:31 -07:00
Drew Paroski 2ddb2189fd Set EnableXHP=0 by default, improve how the lexer works when EnableXHP=0
A couple of developers on github have reported that they've hit errors at
parse time with certain expressions that work under Zend PHP, or that they
have gotten output unexpected tokens from token_get_all(). A lot of this
is related to the lexer/grammar rules for XHP, so an easy solution to fix
a lot of these issues is to set EnableXHP=0 by default and to make some
changes to the lexer to make it more Zend PHP compatible when EnableXHP=0.

Closes #740
Closes #846

https://github.com/facebook/hiphop-php/issues/740
https://github.com/facebook/hiphop-php/issues/846

Differential Revision: D905986
2013-07-31 08:04:49 -07:00
Joel Marcey fdb61a462f Fix a small error in the IR for converting a resource to a string.
Something was just missed in an overall conversion effort. Found this in PHPUnit testing. @ptarjan was quick to diagnose!

Differential Revision: D907670
2013-07-31 08:04:46 -07:00
Mirek Klimos fb3f801604 Correction of D898769
I accidentally landed some old code with the previous diff
D898769. This will just remove it.

Differential Revision: D907355
2013-07-31 08:04:46 -07:00
Mirek Klimos 2b53df33bc Moving generation of generator bodies from compiler to bytecode emitter.
Generators are natively represented by 2 functions, which are now generated
by parser. Not only it's more natural to do this only when we emit bytecode,
but it will also allow us to reuse this logic for implementation of async
functions.

Differential Revision: D898769
2013-07-31 08:04:46 -07:00
Sean Cannella d0bf4ec6b6 remove option that doesn't work in OSS
- remove option from docs that doesn't work in OSS (becuase it
depends on a hacked version of mysql)

Differential Revision: D906111
2013-07-31 08:04:41 -07:00
Edwin Smith b92e3dedb0 Tighten checkRegisters()
Currently, check registers works by traversing down the dominator
tree.  Effects on registers from a dominator block can be seen
in each dominator child.  This will miss a rogue assignment that
happens in a block that does not dominate one of its successors.
For example if we mis-assign to a register in one arm of an if-
then-else block, we won't notice.

This diff changes checkRegisters() to propagate register state
along flow edges, so we can catch such rogue assignments.

Differential Revision: D903949
2013-07-31 08:04:41 -07:00
Sara Golemon 9e82e86d9e Fix handling of "not buildling from git" case
The fallback for repo-schema and compiler-id
generation when not building from git was to use the system
microtime.  Unfortunately, using a '.' in the repo-schema
leads to bad SQL table names.  Use an underscore instead.

Differential Revision: D906623
2013-07-30 12:43:34 -07:00
mwilliams 43a964cc13 Try to fix mysterious __sleep crash
We're seeing that some opt builds crash if you throw from
__sleep. After a lot of debugging, it looks like the eh_frame section
contains a bogus entry for php_sleep (in addition to the correct one),
and eh_frame_hdr's entry points to the wrong one (if I intervene in
gdb and point it to the right one, everything works).

I'm pretty sure this is a bug in gold (the eh_frame data appears
to be correct in object_data.o), and changes to unrelated code
make the bug appear and disappear.

I'm not sure exactly what the issue is, but php_sleep is basically a
hangover from hphpc days, so I'm killing it (and modifying the meaning
of HasSleep slightly - it now means what you expect). Not very satisfying
but hopefully it will work...

Differential Revision: D906292
2013-07-30 12:43:34 -07:00
Eric Caruso 21664d4b84 Add ProfileController, clean up ProfileDump and friends
This new static API will allow the coming pprof server
to request and fetch profiles, and VM threads to offer profiles
if they fulfill the currently active request. Some cleanup was
also performed to refrain from repeating stuff.

Differential Revision: D896872
2013-07-30 10:41:09 -07:00
Eric Caruso 9604aec155 Resolve SrcKeys to symbols so pprof can generate graphs
pprof will request symbols from a running HHVM via
POST request when you try to run it in remote mode. This adds
the ability to format SrcKeys in a reasonably human-readable
format so pprof can deal with them, and it can be manually used
by turning on TRACE=heap:3.

Differential Revision: D895234
2013-07-30 10:41:05 -07:00
Eric Caruso 83d4088bca Implement pprof-style heap profile formatting
Heap profiles can now be dumped in pprof format using
ProfileDump::toString. The memory profile instrumentation now
dumps this data at the end of every request when TRACE=heap:2
is set.

Differential Revision: D894112
2013-07-30 10:41:01 -07:00
bsimmers 3f1230f88f Add inlining support to the legacy region selector
When converting a Tracelet that contains an inlined FCall,
flag its block and then insert block(s) from the callee between the
FCall and the next instruction in the caller. The region translator
also required a few changes to support the inlined blocks.

Differential Revision: D863939
2013-07-30 10:40:56 -07:00
bsimmers a60daf4750 Turn JIT::Opcode into an enum class
Pretty straightforward. I renamed all the Op<name> opcodes to
just <name> to avoid collisions with the bytecode Op<name> constants.

Differential Revision: D867723
2013-07-30 10:40:52 -07:00
bsimmers 58e5f0caf0 Partially fix debugger pseudomain issue
I haven't completely figured out what's going on here, except
that we're running the same Func with and without the global varenv
attached. This was confusing the guard code and so we weren't emitting
guards for a local. This diff fixes up things so we do emit the
guards, but the global varenv issue still needs to be sorted out
before the new assert in translateTracelet can be left on.

Differential Revision: D899963
2013-07-30 10:40:48 -07:00
Eric Caruso b66e6c7a09 Compute square roots in the JIT
Pushes the sqrt builtin down to codegen for ints and
doubles, which might help on some microbenchmarks, and adds
sqrtsd to the assembler.

Differential Revision: D898146
2013-07-30 10:40:45 -07:00
Paul Tarjan 78157a5af5 don't call user-code in constructor
`rewind()` is an overridable method in children. composer does just that, and expects the objects to be fully formed by the time it is called. Lets use a private helper instead, so user-code isn't called in the constructor.

Differential Revision: D904037
2013-07-30 10:40:41 -07:00
Jordan DeLong fdfbbfc39b Memoize xed addressToSymbol callback
Apparently printir is so slow because of the symbol lookups
here.  Let's just leak a memoized table (we probably don't actually
have that many distinct symbols to look up).  Also, it looks like this
code writes one byte further than it's supposed to in the output
buffer (the docs for the xed callback say the buffer_length includes
the null terminator).

Differential Revision: D902605
2013-07-30 10:40:35 -07:00
Jordan DeLong 88b1cedd01 Fix a refcounting bug in Closure destructor
It didn't check if the reference count went to zero.

Differential Revision: D903740
2013-07-30 10:40:25 -07:00
Jordan DeLong 735c6c0cdc Closures with AttrStatic never have an object context
This check in the prologue didn't make sense to me---I'm
pretty sure it's impossible for the branch to be taken, since we've
already set up c_Closure::m_thisOrClass such that it will contain a
Cctx.  Am I missing something?

Differential Revision: D894574
2013-07-30 10:40:15 -07:00
Jordan DeLong 6443636f36 Some optimizations for closure creation
Inline some of the things into the TC so it can be
specialized on the closure type.  Also avoids spilling everything to
the stack to call init (which just pulls it back off and puts it into
the heap), and uses AllocObjFast instead of newInstance.  (We can't
quite get the super-fast-path version of AllocObjFast because closures
are extension objects and for now trying to convince it not to use the
m_InstanceCtor is a bit lame---we should probably just generate the
classes as php-level classes at some point so that'll just work.)

Differential Revision: D894569
2013-07-30 10:40:05 -07:00
Mirek Klimos 2c31ff8515 Letting doOptimize go into closure bodies.
As bodies of closures are not part of standard syntax tree, doOptimize
doesn't optimize them; this diff will fix this. It should have no
impact on performace as doOptimize is not used in WholeProgram mode.

Differential Revision: D904216
2013-07-30 10:40:00 -07:00
Sean Cannella b1762b9a07 fix OSX build issues
Differential Revision: D904206
2013-07-30 10:39:56 -07:00
bsimmers 98672dde4e Kill getKeyType[IS] and fix a emitVGetProp crash
getKeyTypeI/S/IS were artifacts of how keys were passed in
TranslatorX64 and no longer serve a useful purpose. emitVGetProp had
the same issue that was fixed in D902733 (no helper for Int keys).

Differential Revision: D904487
2013-07-30 10:39:50 -07:00
Owen Yamauchi 40104e57ea Remove remnants of parse-tester
Differential Revision: D904174
2013-07-30 10:39:34 -07:00
Paul Tarjan 8a87699411 remove typehints for FilesystemIterator
This class will happily take another `FilesystemIterator` as a param. Let the parent deal with throwing on bad params.

Differential Revision: D898524
2013-07-30 10:39:29 -07:00
Eric Caruso b057b96603 Support list unpacking in foreach keys and values
Zend 5.5 allows you to unpack arrays into the key and
value expressions in a foreach loop. This implements the same
functionality in HHVM.

Differential Revision: D900264
2013-07-30 10:39:25 -07:00
Sean Cannella a168863d5e remove dead option from docs
remove MaxStackDepth from docs, not used/implemented
remove unimplemented memcache-related statistics/settings

Closes #911

Differential Revision: D904848
2013-07-29 15:01:44 -07:00
Joel Marcey bb5dc1bbd2 Implement PHP_BINDIR (core constant)
Implement PHP_BINDIR PHP core predefined constant. PHPUnit (via PEAR) uses this constant in its self-test suite, causing many of them to fail on HHVM (possibly only because of the lack of this constant). Try to ninitially implement in such a way that it can be nimble enough for open-source, cross platform.

Differential Revision: D900077
2013-07-29 15:01:38 -07:00
Sara Golemon 834a1d331f Remove a bunch of separable extensions cruft
This code hasn't been relevant in a long time.

Differential Revision: D904562
2013-07-29 15:01:35 -07:00
Herman Venter 1b3c783dd4 Log status of all curl requests during test
Use exec("curl ...") instead of the curl API to make server requests, so that every interaction with the server can be traced and logged.

Differential Revision: D902614
2013-07-29 15:01:30 -07:00
Owen Yamauchi f4273f2c79 Normalize spelling of "prologue"
We had both "prologue" and "prolog" all over the place, and it was
starting to drive me nuts. I picked "prologue" because it seems to be
the more standard spelling. Both are valid in American English, but in
the rest of the English-speaking world, only "prologue" is standard.

Differential Revision: D904232
2013-07-29 15:01:25 -07:00
Daniel Sloof 9e36d6a2ae parallelize test runner on non-Linux platforms
parallelize test runner on non-Linux platforms

Closes #903

Differential Revision: D904203
2013-07-29 15:01:20 -07:00
Paul Tarjan 3ba3bccbc9 don't run phpunit test in repo mode
phars don't work in repos
2013-07-29 12:11:06 -07:00
Paul Tarjan 21780cb8e5 implement undocumented feature of RecursiveIteratorIterator
So this works in zend and composer relies on it, so I guess we should make it too...
2013-07-29 12:11:05 -07:00
Paul Tarjan 63bb1e6bf3 add phpunit test
I was having trouble gettig the binary into phabricator so the test wouldn't pass, so I committed the phar anyways. Now that the phar is in, a test should see it.
2013-07-29 12:11:05 -07:00
Paul Tarjan 063e9e75f7 don't return bad json
If there was an error during parsing, we shouldn't return anything.
2013-07-29 12:11:04 -07:00
Stephen Chen 57896cadfe Add priority to hphp's job queue
Add priority to hphp's job queue. Basically internally we keep multiple
queues. Whenever a worker gets notified of a job, it'll look at each queue in
order from highest pri to the lowest pri. This is inefficient if we have a large
number of priorities. But in reality we'll only have a handful of priorities. So
this should be faster than a heap implementation.

Add a runtime option to be able to specify a set of end points to be prioritized
over regular requests.

In practice, we'll only have 2 priorities, high and normal. For high, we only
plan to put status.php there. This is so the web server can respond to health
check even under high load.
2013-07-29 12:11:04 -07:00
Drew Paroski 707500591c Remove some deprecated collection APIs that are no longer used
There are a number of deprecated collection APIs that are no longer used
(all uses of them were removed over a week ago). Let's get rid of these.
2013-07-29 12:11:04 -07:00
Edwin Smith 59411c4a48 Add support for capturing stack samples, then counting them later.
StackTraceProfiler.count() captures a stack trace at the point you call
it.  It's also useful to create a stacktrace, then add it to a profiler
later on.  For example, create a stacktrace when you allocate an array,
then count it when the array reaches some state (destruction, growing,
changing shape, etc).
2013-07-29 12:11:03 -07:00
Edwin Smith bc03e4fad4 Use StaticStrings in getDataTypeString()
Doing some profiling of litstr creation, I noticed f_gettype() being
called a lot, but not using static strings.
2013-07-29 12:11:03 -07:00
Drew Paroski 53a869d1d6 Fix how "$obj -> class" is lexed
At present, "$obj -> class" (with spaces) causes a parse error under HHVM
but it parses okay on Zend. The problem is that HHVM's lexer treats "class"
as a keyword when there are spaces after the "->". This diff fixes HHVM's
lexer appropriately.

Closes #833

This fixes https://github.com/facebook/hiphop-php/issues/833 .
2013-07-29 12:11:02 -07:00
Jordan DeLong 7587932213 Remove hphp/util/parser/test
I added this in hopes it would make it easier to do parser
development faster---in practice I find myself preferring to just wait
on the build times for compiler/parser instead.  Changes to the parser
too often involve the need to fix the crazy callback interface over
there, and it's not worthwhile to maintain it in two places.  Oh well.

Making the parser more modular to develop on is probably worthwhile
but I'm calling this a failed attempt.

In case it scares anyone that I'm deleting tests: this test suite
wasn't really intended to find bugs, but I think it's unlikely it
would (the normal tests have to parse everything anyway).
2013-07-29 12:10:12 -07:00
Jordan DeLong 337160161d Fix an issue with CGetM on objects with an integer property keys
The implementation was trying to look up a specialization for
ints, but there isn't one, so it would hit an assertion on opFunc in
debug and call to a null address in release.
2013-07-29 12:10:12 -07:00
Jordan DeLong 8f2476ff5e Fix segv when class_alias is called with zero args
m_params is a null pointer when there's no arguments.
2013-07-29 12:10:12 -07:00
Edwin Smith 89c362e341 Clean up StaticString declarations
We've used a couple different styles, this consolidates on a single
style and moves a few declarations out of function bodies to global
scope.
2013-07-29 12:10:11 -07:00
Paul Tarjan cb4662c436 fix asCResRef
I wrote this before the resource diff landed.
2013-07-29 12:10:11 -07:00
Paul Tarjan b1f633f91d implement stream_is_local
needed for composer installation
2013-07-29 12:10:07 -07:00
Drew Paroski d3c421cb79 Separate resources from objects, part 2
In HHVM we've been piggybacking resources on the KindOfObject machinery.
At the language level, resource is considered to be a different type than
object, and there are a number of differences in behavior between objects
and resources (ex. resources don't allow for dynamic properties, resources
don't work with the clone operator, the "(object)" cast behaves differently
for resources vs. objects, etc).

Piggybacking resources on the KindOfObject machinery has some downsides.
Code that deals with KindOfObject values often needs to check if the value
is a resource and go down a different code path. This makes things harder
to maintain and harder to keep parity with Zend. Also, these extra branches
hurt performance a little, and they make it harder for the JIT to do a good
job in some cases when its generating machine code that operates on objects.

This diff introduces a new DataType called "KindOfResource", it separates
ResourceData from ObjectData's inheritance hierarchy, introduces a new
smart pointer types called "Resource" and "SmartResource", updates the
runtime as appropriate, and kills some more dead code in ObjectData and
ResourceData. I've tried to keep behavior the same for the most part and
resisted the urge to fix existing bugs with resources.
2013-07-29 11:25:56 -07:00
Guilherme Ottoni a1f16ea646 Kill comment about completed task
I forgot to take this out with D900055.
2013-07-29 11:25:00 -07:00
Guilherme Ottoni c0016ae59b Dump aprof code into separate file and teach tc-print about it
This avoids dumping a tc_dump_a file of more than 512MB.
2013-07-29 11:25:00 -07:00
Sara Golemon 8d9ae2c179 Remove retired options from CMake/Options.cmake
ENABLE_LATE_STATIC_BINDING
INFINITE_LOOP_DETECTION
REQUEST_TIMEOUT_DETECTION
HOTPROFILER_NO_BUILTIN
INFINITE_RECURSION_DETECTION
WANT_FB_LIBMCC
2013-07-29 11:23:45 -07:00
Jordan DeLong 0fa12ac543 Move JSON_parser stuff out of global namespace 2013-07-26 11:31:19 -07:00
Jordan DeLong b38e53d0e7 Add "static" to most InitFiniNodes
Some of them were neither static nor in an unnamed namespace.
2013-07-26 11:31:19 -07:00
Jordan DeLong dd9ecf559e Don't use malloc from pcntl_signal_handler
Not kosher.
2013-07-26 11:31:19 -07:00
Sara Golemon 095e163a1d Use m_conn rather than PDOStatement::dbh within PDOMySqlStatement
It's possible for PDOMySqlStatement to try to access
dbh before it's initialized, but m_conn will be set by the ctor.

Closes #851
2013-07-26 11:31:19 -07:00
Martin Matuska 778abf7ab1 ifdef Linux-specific GNU extensions/impls as such
- mark Linux-specific extensions as such
2013-07-26 11:31:18 -07:00
apuckey e70567994c fix shutdown crash when using PDO
- fix shutdown crash when using PDO

Closes #710
2013-07-26 11:31:18 -07:00
mwilliams b2bf67f7e5 Fix pagelet timeouts
Push the remaining time through to the pagelet's HttpRequestHandler,
and fix HttpRequestHandler::handleRequest to use the timeout we pass in
(the latter was an inadvertent omission from my previous timeout diff).
2013-07-26 11:31:18 -07:00
mwilliams cd5e74ec7e Fix type inference for ZendParamMode
Parameters of ZendParamMode functions aren't converted to the
destination type, so don't try to apply a type.
2013-07-26 11:31:18 -07:00
Bert Maher 88640588e3 Move NormalizedInstruction out of translator.h
In the name of making incremental builds faster when headers
change, I've pulled NormalizedInstruction out of translator.h and
replaced it with a forward decl.
2013-07-26 11:31:17 -07:00
Mike Magruder fb9f1405ce Remove ctrl-c test from debugger server test
We can never make the ctrl-c portion of the debugger server test 100% reliable. Removing that portion of the test. I'll replace it with something else soon. See task 2656173.
2013-07-26 11:31:17 -07:00
bsimmers ecf6c0a726 More cur*() -> live*() renaming 2013-07-26 11:31:17 -07:00
bsimmers 48dc5639f1 Rename curFunc() to liveFunc() 2013-07-26 11:31:17 -07:00
bsimmers c16d3b3536 Rename curUnit() to liveUnit()
curUnit and friends are evil and have been the source of many bugs
I've had to track down in the region translator. Time to force an audit of all
callsites. Most of the uses of curUnit() could be changed to grab the unit from
somewhere else, and the few where that wasn't reasonable use liveUnit to make
the intent more clear.
2013-07-26 11:31:16 -07:00
Bert Maher a1e6cb1ca1 Reduce boilerplate in RuntimeType constructors
RuntimeType has a lot of constructors that could share some
code, so I factored the common stuff into a private init() method.
2013-07-26 11:31:16 -07:00
Mike Magruder 05871951f0 Debugger: cleanup server-side when the client disconnects while in run mode
Server-side cleanup was all driven by having a request thread see that either the connection with the client is closed, or the stopped flag on the proxy is set. However, if a debugger's in the run state and there's just no incoming requests against the right sandbox, then that would never happen. However, the signal polling thread is perfect to notice, there were just issues coordinating the cleanup of the proxy.

Modified stop() on the proxy to be callable from any thread, and to initiate cleanup of the proxy but pass the final cleanup off to another thread which can complete it. The signal polling and dummy sandbox threads are owned by the proxy, so they can't complete the work themselves. There was logic to queue cleanup just for the dummy sandbox, so I turned that into proxy cleanup and have it cleanup both.

I'll investigate making a unit test using the new framework that will test this, but that will come in a later diff since this diff is already quite involved.
2013-07-26 11:31:16 -07:00
Ben Maurer a9e05eabf4 Shutdown listen socket during segfault
During a segfault, we continue to accept incoming connections. This is
bad as the web server is unlikely to do a good job of serving these well.
Here we close the listen socket as soon as we discover the server is crashing.

A more robust way to do this might have been to have an array of FDs that
are listening for incoming connections. We could have then closed those
from the signal handling thread. This would complete the operation more
quickly and also handle a case where the libevent thread wasn't running.
However, this version was quicker to write.

I didn't understand why some signals didn't trigger the Segfaulting variable.
Does anybody have insight into that?
2013-07-26 11:31:15 -07:00
Stephen Chen a112d17438 Add an option to hhvm to 503 requests if they have been sitting on the select queue for too long.
Add an option to hhvm to 503 requests if they have been sitting on the select
queue for too long. Threshold is configurable via runtime option and default off
for now. This works with either LIFO or FIFO mode. Basicallly before worker
dequeues a request, it peek at the beginning of queue to see if it's expired. If
so, it takes that off the queue and aborts the request without executing
anything.
2013-07-26 11:31:15 -07:00
Herman Venter b7ed094ed2 Use the same output formatting for = command as is used for the print command.
The = command uses formatting that is user customizable and subtly different, by default, from the formatting used by the print command and the variable command. This has historical roots. It seems that the debugger used to use print_r, which is brittle, and the customization hook was introduced to work around this brittleness. This work around is no longer necessary since the debugger now has its own, robust way of formatting values as strings. Also, the difference between = and print is a perennial source of confusion for debugger users.
2013-07-26 11:31:15 -07:00
Herman Venter 5d494456bc Display more diagnostic information in the case of test failure
When there is a failure in the test of debugging a server, give more diagnostics about failures to connect to the server.
2013-07-26 11:31:15 -07:00
Mike Magruder 0cc77bde72 Adjust error handling around socket closure for debugger
I had previously made the error handling in DebuggerCommand::Receive() too strict, and we'd fail to read available data from the socket when it was closed right after the data was sent. Loosened it, so if there appears to be data present we'll let the thrift layer have a chance to read the data.

I also moved the remaining log messages in that function to traces. There are cases where it is nice to see such a log message printed, but those are very rare and have not happened in the wild in the past many months. Log messages here particularly from the signal polling thread make our test output non-deterministic, and there's higher value in having stable tests :)
2013-07-26 11:31:14 -07:00
Drew Paroski 64b284d281 Fix silly bug when computing AttrDeepInit for a property
This diff fixes a crashing bug that can happen when multiple properties are
declared in a single statement and some of the properties are initialized
using collection literals, for example:

  public $x = Set {}, $y = 1;
2013-07-26 11:31:14 -07:00
Paul Bissonnette d63459b8e5 Adding floor and ceil to interpreter/jit
Added floor and ceil to the interp and jit, also fixed some type conversion simplifications.
2013-07-26 11:31:14 -07:00
Edwin Smith 5b42995fbd Fix leak in HphpArray::PopVec
If you pop the last element of a vector-shaped array,
we didn't decref the value or update the iterators properly.
2013-07-26 11:31:13 -07:00
Vanilla Hsu 2592a77248 fix embedded_data on freebsd
- remove hardcoded path in embedded_data
2013-07-26 11:31:13 -07:00
Chip Turner c051b9c3c2 Fix return types from AsyncMysql queries (allow NULLS, support variants)
We did not properly export NULL values as null; instead they
appeared as empty strings.  In addition, we returned all ints, floats,
etc, as strings rather than properly typed.

This diff adds support for typed return values (ie, ints, floats, etc)
rather than just strings.  It also changes returned maps and vectors to
have actual null values when the underlying result set returned nulls.
2013-07-26 11:31:13 -07:00
Joel Marcey a7c6c411e2 Support zend_version()
PEAR uses zend_version(). Let's support it too.
2013-07-25 14:00:11 -07:00
Sean Cannella a43fbbce08 disable failing test
This worked when imported
Due to a diff that was reverted
Because it broke other things
2013-07-25 13:59:56 -07:00
Paul Tarjan 647e3a7148 fix zend error message
I stupidly changed this without retesting. The message shouldn't have a newline in it.
2013-07-25 13:59:56 -07:00
Herman Venter fe3ca642be Remove obsolete debugger test suite
The debugger tests that are run via hphp/test/ext/test have now been replaced by tests that run via hphp/test/run, so they can be deleted as they test nothing additional and appear to be flaky.
2013-07-25 13:59:56 -07:00
Sean Cannella d618b30ed7 no POSIX timers on OSX
- unbreak OSX build

Closes #891
2013-07-25 13:59:55 -07:00
Sean Cannella 4eb23b6687 Revert "simplexml fixes for text children and casting" 2013-07-25 13:59:52 -07:00
Kyle Delong 70e0cf3568 HPHP/XHP: always pass file/line into XHP constructors 2013-07-25 13:59:40 -07:00
Paul Tarjan ad394c4f06 import phar tests
Now that phars sort of work, we can import their tests and they don't spew everywhere.
2013-07-25 12:10:59 -07:00
Paul Tarjan ed852dee7a implement read support for phars
A first pass at phar. The parsing logic was done from the spec:
http://www.php.net/manual/en/phar.fileformat.phar.php
2013-07-25 12:10:58 -07:00
Guilherme Ottoni 2f7088b1b3 Add an aprof code region and use it for profile translations in JitPGO mode
This diff generalizes the AHotSelector (now called AsmSelector) to
select an assembler among 'a', 'ahot', and 'aprof'.  'aprof' is only
allocated and used in JitPGO mode, and it's used for TransProfile
translations.
2013-07-25 12:10:58 -07:00
Paul Tarjan 8bec0a9f9c use correct class for RecursiveDirectoryIterator
That was one hell of a bug. They overwrote a subclass and expected the overwriting to stay when it created a new copy.
2013-07-25 12:10:57 -07:00
Paul Tarjan 6faa4e2ca6 handle file:// includes
Now that we can include urls, we shoudl handle `file://`.
2013-07-25 12:10:57 -07:00
Sara Golemon 9627f855ce Move RuntimeOption settings for APC section to ext_apc
Avoid the massive monolithic structure that it
runtime_options.cpp

Rename settings along the way to drop superflous "Apc" naming.
2013-07-25 12:10:57 -07:00
Eric Caruso 8ac589b4b7 Leak Units when memory profiling to prevent cleanup of Funcs and Classes
Memory profiling is going to rely on these things not getting
destroyed, so we are intentionally going to leak them in this case.
The use case of this is that the memory profiler is going to store
a stack trace as a bunch of SrcKeys, which can be used with D892173
to look up the original Func the stack trace goes through. Since we are
looking up the Func potentially much later than the SrcKey was
originally recorded, there is no guarantee that the Func will still be
around, or that we won't grab a pointer to it only to find that it is
in the middle of destructing and is thus full of garbage.
2013-07-25 12:10:56 -07:00
Eric Caruso 2a793e36dc Instrument smart allocator
Dumps information about allocation events in smart
allocator, and aggregates some information such as bytes
allocated per callsite in the current request (or across
requests). This information can be gathered in the heaptrace
command, and the information collected during the trace is
enough to find how much memory an object is responsible for
(i.e. keeping reachable).

It's all conditionally compiled because perflab showed a pretty
significant instruction regression if it was a runtime option.
You'll need to fbconfig with --extra-cxxflags=-DMEMORY_PROFILING
in order to use it.

This isn't done, but I wanted to get some feedback on where I
should take this (general design, what to log, where to dump
stuff, etc)
2013-07-25 12:10:56 -07:00
Eric Caruso a06d5fcbdf Add structs for holding heap profile dumps
These structs will eventually hold the heap profiling data
for PHP request heaps, so that it can be gathered and displayed
using the pprof tool.

This was tested by layering the smart allocator stuff on top and
making sure everything worked as planned. Nothing uses the structs
in this diff, so it's kind of difficult to test otherwise.
2013-07-25 12:10:55 -07:00
bsimmers d09abeb26d Support parameter reffiness in the tracelet region selector
This brings the tracelet region selector to 100% coverage,
though perf is still not at parity. Guard relaxation/specialization
and inlining are the big remaining features that will help perf.
2013-07-25 12:10:55 -07:00
bsimmers 631438f0fb Apply metadata to the ir in translateTracelet
In one of my pending region compiler diffs, I added code to forget the
values/types of locals after some FCalls (not doing so was wrong but we were
mostly getting away with it). This exposed an issue where the known type of a
local in the IR was less specific that what Translator::analyze was using. The
more specific type came from metadata on instructions after the FCall, so this
diff applies metadat to the IR before translating each instruction, using the
same code I wrote for the region compiler.

The changes to apply the metadata are pretty small; most of the
changes in this diffs are real bugs I found while attempting an
alternate solution.
2013-07-25 12:10:49 -07:00
Chip Turner 6bc3bf2d82 Change interface to ext_mysql C++ code to allow transporting underlying conns
This allows for connections to be created from existing mysql
connections as well as extracting the underlying connection from it.
2013-07-25 10:56:08 -07:00
Owen Yamauchi d0fdcfaef6 Fix warnings for various things being passed by reference
We were fataling when passing a list assignment expression with an
array-element RHS (like "$arr[0]") as an argument that the callee
expected to take by reference. Zend allows this, but with a warning. I
figured out the rules as best I can (this is one of those corners of
Zend where layers of insanity have piled up over time). I won't swear
that I got it 100% right w.r.t. whether we warn or not, but I'm pretty
sure we're closer to 100% right w.r.t. whether we fatal or not.
2013-07-25 10:56:08 -07:00
Owen Yamauchi 6451f9fc04 Delete GlobalCache, take 3
Pulling the trigger; it's unused post-tx64. This diff preserves the
ability to mark units as merge-only when the pseudomain only contains
assignments to known globals. When the unit is being merged, the set
operation goes directly to the global varenv instead of through the
targetcache (GlobalCache stored pointers into the global varenv's
NameValueTable).
2013-07-25 10:56:08 -07:00
Paul Tarjan 1c50cde17c fix subPath for RecursiveDirectoryIterator
Another RecursiveDirectoryIterator bug :( This time, subPath was totally wrong. It should only be adding on a little bit each time, not the whole path.
2013-07-24 10:35:47 -07:00
Paul Tarjan c1af7f57f5 fix str_split
This was coming up when installing Symphony using composer, and while I was in there I fixed a zend mode bug. We weren't doing the warning in the interpreter (and we were doing null instead of uninit). That was enough to move most of the tests over. The other problem is tasked.
2013-07-24 10:35:47 -07:00
mwilliams fe42263267 Fix lock rank violation assersions
There's a race in the emitter, where if we emit a unit (because,
it wasn't in the repo) fail to commit it, and then find the unit in the repo,
we destroy the unit we just emitted, and read the one from the repo instead.

This typically happens at RankFileRepo. A new change to Func::~Func makes
it grab the write lease in DEBUG builds, which is a lock rank violation.

Newly created Funcs never need the write lease, however, so aquire it
lazily.

This was happening running slow tests, because some tests are run multiple
times (potentially in parallel) with different runtime options (in fact, the
test code is duplicated in separate files).
2013-07-24 10:35:47 -07:00
Owen Yamauchi 5978586214 Import VIXL, an ARMv8 assembler/disassembler/simulator
This diff is intended primarily as a medium for everyone to look at and
discuss the code I'm planning to use as our ARMv8 in-memory assembler
and simulator. This is what I was about to spend weeks and weeks writing
myself, but thankfully ARM has done all that for us!

To get an idea of what it looks like to use VIXL, look at
test-assembler-a64.cc, at lines that begin with "__". Superficially, it
looks very similar to clients of X64Assembler. Things like x0, w1, etc.
are registers. "Operand" is a struct that encapsulates some of the extra
stuff tacked on to ARMv8 instructions -- e.g. when comparing against an
immediate, you can include a left-shift amount for the immediate, and it
will look like "Operand(x1, LSL, 1)" or similar.

The simulator is similarly easy to use. You set initial register values,
give it an instruction pointer, and say go. It runs until it hits a ret
instruction that takes it out of the top level, and then you can read
register values out of it. It can access memory just like native code
can.

VIXL includes its own abstraction for registers, and it's structurally
quite similar to our PhysReg. (It's defined in assembler-a64.h.) One of
the most nontrivial parts of this effort will be to figure out how to
unify these two abstractions.

The instruction coverage is internally consistent (i.e. the simulator
and disassembler can deal with any instruction the assembler can output)
and is almost certainly enough for our needs. Even if it's not, the code
is pretty clean, and it won't be hard to add whatever we need.

The big thing I'm not yet sure about is the implementation of nonlocal
jumps. The usage examples that come with VIXL (but I'm not including
here; see the original github) use jumps, but only within the small
snippets they emit. There's nothing that resembles our jumps between a
and astubs. This might be something we have to hack in, but it shouldn't
be too hard. The one potentially tricky part will be to support jump
smashing. If we have to encode a jump as multiple instructions, we won't
be able to smash it atomically. The only viable alternative I can think
of is to have a "jump target table" on the side, emit an indirect jump
in code, and smash the table entries instead of the code.

The open-source distribution of VIXL is built with scons, but it was
near-trivial to get it building with our internal system. To build the
library, I just had to change the include paths. To build the tests, I
deleted the custom test driver that came with VIXL and converted the
test files themselves to use gtest. This was mostly a matter of tweaking
the macros to use gtest asserts.

I also fixed lint errors (NULL -> nullptr, include ordering, static at
namespace scope, ...)

About licensing. The code is under a 3-clause BSD license, and the
license header is preserved in all the files I pulled in.

Pulled from https://github.com/armvixl/vixl at ad96eda894.
2013-07-24 10:35:46 -07:00
Sara Golemon 1824c359ea Pass entire Hdf to Extension::moduleLoad()
This lets us move parsing of runtime options
to the extensions which actually use them.

Nobody is currently using this functionality, so changing
what gets passed isn't a BC break worth worrying about.

I'll post some followup diffs pulling things out of
RuntimeOptions.
2013-07-24 10:35:46 -07:00
Paul Tarjan b1d102c698 import all 5.5 tests
and spruce up the import script while I'm in there. Lots of new tests 'passed' because of the skipif

We are now at 45.4% pass rate
2013-07-24 10:35:45 -07:00
Guilherme Ottoni d078c2b895 Add initial framework for PGO in the JIT, and use it for trace-region selection
This diff adds an initial framework for profile-guided optimizations
in the JIT.  Two new translation modes are added, effectively creating
a multi-gear JIT:

  1. Profile: this collects profiling data, which includes execution
              counters and type information.
  2. Optimize: this uses data collected by Profiling translations to
               produce optimized translations.

Right now, the Optimize gear is solely used to produce larger
compilation regions (traces), which increase the scope of
optimizations exposed to the JIT (compared to tracelets).  This is
still work in progress, and it's disabled by default.

This diff also fixes a number of bugs exposed by trace regions, gets
tools/reduce working again, and makes a number of improvements to
tc-print related to the new translation modes.
2013-07-24 10:35:45 -07:00
aravind 0d0748302c Smash function prologues on function destruction
Function prologues guard on Func* pointers rather on funcId.
This can cause a recycled Func* (with a different funcId) to
pass the prologue guard. Change it so that the Func* destructor
smashes the func prologue guard immediate.
2013-07-24 10:35:44 -07:00
Edwin Smith b9812e548a Change AttachLiteral to CopyString everywhere
This is a big codemod but has no effect; the actual change
was from D894412.
2013-07-24 10:35:44 -07:00
Edwin Smith 2e293e471e Eliminate AttachLiteralMode
Eagerly copy strings instead, getting us one step closer
to in-situ allocation for all StringDatas.
2013-07-24 10:35:44 -07:00
bsimmers 7aa354b270 Add build flags to control the region selector default
This will be used to run automated builds testing the new
region selectors.
2013-07-24 10:35:43 -07:00
Martin Matuska 1a5cc943e5 fix HHVM compilation on FreeBSD
- fix HHVM compilation on FreeBSD

Closes #874
2013-07-24 10:35:43 -07:00
mwilliams a946a8eb35 Get rid of TimeoutThread(s)
Use timer events instead. A side effect is that we now
support timeout in client mode. We also get much more
accurate timeouts. Previously starting a server with
a timeout of 4s, and GETing an endpoint that just looped,
would timeout somewhere between 3.5(!) and 8 seconds. Now
it times out between 4.0001 and 4.02s.

This will also make fixing pagelet timeouts much easier.
2013-07-24 10:35:43 -07:00
Daniel Sloof 2ac92de922 simplexml fixes for text children and casting
- fixes text children count and bool cast of empty nodes
2013-07-24 10:35:42 -07:00
Paul Tarjan 961d3add9e php_strip_whitespace
Close to zend's. Needed for composer.

I can't move the real zend test over since we don't apply zend's calling convention to systemlib (yet).
2013-07-24 10:35:42 -07:00
Vanilla Hsu 159c001f24 support current_executable_path on FreeBSD
- add support for current_executable_path on FreeBSD

Closes #878
2013-07-24 10:35:41 -07:00
Paul Tarjan 1845ed29b8 put fb_lazy_lstat back in the JSON
I got overzealous in my vim macros. Editing this JSON file is hard, sorry.
2013-07-24 10:35:41 -07:00
Jordan DeLong ab9652c99a Fix weird assignment operators in ScannerToken and Token
Copy assignment operators should generally take const lvalue
references and return non-const lvalue references to the lhs.  It's
unclear why these don't (probably no reason), so fix it.
2013-07-24 10:35:41 -07:00
Jordan DeLong 7df1338063 Remove unused undef stuff in bytecode.cpp
Vestigial.
2013-07-24 10:35:40 -07:00
Jordan DeLong a466faf52d Implement more of php assert()
Adds support for string arguments to assert (outside of repo
authoritative mode), and support for ASSERT_QUIET_EVAL.
2013-07-24 10:32:26 -07:00
Jordan DeLong d709f1c6b1 Make fooIsPlausible functions take args by value
Also, checkTv is redundant now, since I added the refcount
assertions to tvIsPlausible earlier.
2013-07-24 10:32:26 -07:00
Jordan DeLong e250fd6336 Implement bitwise negation outside of Variant 2013-07-24 10:32:26 -07:00
Jordan DeLong 5732b1c491 Remove tvReadCell; use cellDup, sometimes with tvToCell instead
This function used memcpy on TypedValues where it doesn't
know the storage location, which is dangerous if the target lives in a
HphpArray (or anything else that uses m_aux).  It also just seems like
it's now an unnecessary/redundant entry point in the typed value API.
Several uses of it are on things that can't be KindOfRef anyway (I
fixed constants, but where I wasn't sure I used tvToCell first).
2013-07-24 10:32:25 -07:00
mwilliams b400bfb015 Add an override for CoreFileSize
If present, CoreFileSizeOverride overrides the setting of CoreFileSize.
2013-07-24 10:32:25 -07:00
Jordan DeLong 0992cadf6f Implement inc/dec outside of variant 2013-07-24 10:32:25 -07:00
Paul Tarjan 5b367ac44a use all alias for travis
we want to run all suites, so lets let the test framework decide what that means
2013-07-23 16:42:21 -07:00
Martin Matuska 01858fbdce Remove inappropriate filter file from tests 2013-07-23 14:31:18 -07:00
bsimmers ae39c7330e Fix AtomicVector::ensureSize
I should've used unique_ptr::release() instead of unique_ptr::reset(),
but I decided to stop using unique_ptr altogether since gcc generated nicer
code without it. I also eliminated a redundant load of m_next.
2013-07-23 11:44:33 -07:00
Altan Alpay 8457c6232d sprintf() (and thus usprintf, etc) is null-unsafe
Fixing a potential security flaw in sprintf() caused by string parameters
containing mid-string null values to cut off output string prematurely.

eg sprintf("[%s]", "a\0b") === "[a"
2013-07-23 11:44:33 -07:00
Herman Venter acd68c4899 Check that the names used in function name breakpoints are valid PHP identifiers
Breakpoints of the form func() used the same routine to scan names as breakpoints of the form filename:lineno. This meant that you could write something like obj->func() and not get an error message. To fix this I've added a validation routine that is invoked when it has been determined that a name is part of a function name.
2013-07-23 11:44:32 -07:00
Paul Tarjan 27473154bc remove unused builtin functions from hhvm 2013-07-23 11:44:32 -07:00
Paul Tarjan 42490349ef make stream_select return feof streams
Thankfully an easier change than I had hoped thanks to @sgolemon. This will hopefully let us run Symphony's `proc_open` wrappers.
2013-07-23 11:44:32 -07:00
Paul Tarjan e7e0596ab0 remove default boolean params from File::TranslatePath
Most callsites use the defaults, and I can't figure out which callsites should and should not use it. Lets just have different functions for each use-case.
2013-07-23 11:44:31 -07:00
Paul Tarjan 22ec82a1af make include path work with stream wrappers
For phars, I need

  include "phar://some/file.phar/sub/file.php"

to work. I'm trying not to hurt the common path of using files.
2013-07-23 11:44:31 -07:00
Paul Tarjan 15b04a6097 delegate some syscalls to the stream wrappers
Needed for phars. People are doing

  file_exists('phar://a.phar/b.php');

I didn't do all syscalls like `chmod` or `symlink`. Think I should bite the bullet, or do it piecemeal when needed?
2013-07-23 11:44:31 -07:00
Paul Tarjan 9ce7792d8d implement RecursiveArrayIterator
I went through all the tests that mentioned this and looked at them. All of them don't pass because of other missing SPL problems not related to this class (and this class is simple so I wouldn't assume them to blame to it).

Closes #766
2013-07-23 11:44:30 -07:00
Jordan DeLong 10dacc2b44 Change hasThis to check ActRec::m_this & 1 again
It was checking & 3, and I couldn't figure out why.  It looks
like it was introduced probably accidentally by D498715.
2013-07-23 11:44:30 -07:00
Jordan DeLong 94703af1f4 Use ExtraData for LdCtx's compile-time Func parameter 2013-07-23 11:44:29 -07:00
Jordan DeLong 5c569b9d9e Tweaks to AllocObjFast relating to allocating extension classes
When there's an instance ctor, it's not necessary to do the
memcpy for properties or other ObjectData-initialization duties (the
instance ctor does this).  Also, use extra data for the compile-time
constant Class*.
2013-07-23 11:44:29 -07:00
Mike Magruder 8283969d81 Don't serialize cppext instances unless they opt-in, and pass the class name for the debugger
Most CPP extension classes don’t think about serialization, and some require more initialization than the default contractor provides. The result is that on deserialization we end up with a partially initialized object, and undefined behavior after that.

Modified the serializer to emit __PHP_Unserializable_Class instead, and just the class name for the debugger case. Modified the deserializer to create a __PHP_Unserializable_Class, too, if we are given a string with a CPP extension instance in it, so we're safe on both sides. I do not raise a warning; the results are pretty clear, I think, and it's also unlikely that most such warnings could (or should) be corrected. Finally, I also removed the odd behavior of emitting "dummy" classes for Closure and Continuation. I found no use of these in any source tree. Closure had no implementation at all, and Continuation had an implementation that simply raised a fatal on any method call. Thus we can safely assume that even if someone was serializing one of these types, they were receiving an object that was useless to them, or would fatal. So I believe this transformation is safe.
2013-07-23 11:44:16 -07:00
Daniel Sloof 77fb706e57 fix build error on OSX
- fix typo in embedded_data.cpp
2013-07-23 11:44:15 -07:00
aravind 6decb7dcc5 Fix build 2013-07-23 11:44:15 -07:00
Edwin Smith 27e29de6f4 Move _count to offset 12, and rename to m_count.
This allows us to swap TypedValue.m_type and m_aux, which puts
m_type at offset 8 and simplifies the necessary code for passing
TypedValue by value.  It also makes the m_type and m_data fields
of TypedValue contiguous.
2013-07-23 11:44:14 -07:00
aravind 95664338cb Revert "Treadmill for shared variants" 2013-07-23 11:44:12 -07:00
Mirek Klimos 62955d0af1 EmitterVisitor::emitPostponedMeths refactorization
EmitterVisitor::emitPostponedMeths was terribly long and disorganized.
Let's split it into more methods that can be later reused for emitting
generator body in FuncEmitter.
2013-07-23 11:44:11 -07:00
Edwin Smith 4864526172 Add NEWS files
initial files for release notes.
2013-07-23 11:44:11 -07:00
bsimmers 40cbd52dec Increase the starting size for the funcId AtomicVector
Sounds like there might be a bug in the growing logic. This
is just a stopgap until I get a real fix.
2013-07-23 11:44:11 -07:00
aravind 3606603fbd Revert "clean up SharedMap" 2013-07-23 11:44:08 -07:00
mwilliams f57bc3bf88 Revert "Delete GlobalCache" 2013-07-23 11:44:05 -07:00
aravind 58c4c797c5 Revert "Remove the SharedVariant pointer from StringData." 2013-07-23 11:44:01 -07:00
mwilliams 236f9d427c Revert "IterInit, IterInitK, IterNet and IterNextK specializations and guards" 2013-07-23 11:43:56 -07:00
bsimmers 858caa32d1 Maintain a mapping from funcId -> Func*
This diff adds AtomicVector (see comment in atomic_vector.h
for what it is) and uses it to maintain a mapping from funcIds to the
corresponding Func*. This is then used in sktrace instead of
curUnit(), since curUnit() isn't guaranteed to be the Unit the SrcKey
in question came from.
2013-07-23 11:37:12 -07:00
Edwin Smith a9479c7059 Eliminate CreateLvalPtr and GetLvalPtr
HphpArray::CreateLvalPtr does the same thing as LvalStr().  SharedMap
and NameValueTableWrapper::CreateLvalPtr just fatal, and aren't called
anyway.  GetLvalPtr is only called from one place which suppresses COW
and thus can also be done with nvGet, leaving getLvalPtr dead.
2013-07-22 11:34:12 -07:00
Ben Maurer ef1e94eee2 Only let one thread fadvise at a time
On Linux, fadvise forces unwritten pages to be flushed to disk before
returning. This means that under heavy disk IO, all threads could be
waiting on the fadvise call.

This diff uses atomic operations to ensure that only one thread can
do IO at any given time. In addition, it makes any fadvise calls
tail the end of the file by 1 MB. This reduces the chance that
fadvise will trigger IO at all.
2013-07-22 11:34:12 -07:00
Owen Yamauchi 9d5b8a9d5b Delete some dead code in FileScope
hphpc relic. I discovered this while working on $GLOBALS-in-HphpArray.
2013-07-22 11:34:11 -07:00
bsimmers 75751d201c Run object destructors before clearing autoload handler
Our request shutdown procedure cleared the autoload handler
before running destructors of any remaining objects. This was causing
fatals when some of those destructors tried to use a
class/function/constant that hadn't already been autoloaded.
2013-07-22 11:34:11 -07:00
Edwin Smith 1140d2f313 Rename typedef Var to Ref (its a reference)
And, several helper functions with the prefix "var" were changed
to the prefix "ref".  I reworded the bytecode spec; the flavor letter
for PHP references is still 'V', but I reworded parts of it to use
the term 'pointer' instead of 'reference' in places where reference
was too overloaded.  Renamed 'var' to 'ref' throughout.
2013-07-22 11:34:11 -07:00
Edwin Smith 7ad09ea866 Specialize vector & generic copies in HphpArray
This is some carnage left over from the Vector & devirtualize-ArrayData
work. Several places I left the original call to copyImpl(), where a
more specific call would have been ok.  In one place, I called the wrong
function, which would assert in debug and potentially crash in opt.
2013-07-22 11:34:11 -07:00
Paul Tarjan 213496f479 fix gzfile_basic.php
This test failed on tuseday from a file race. Some other test uses the same name. I also preemptively fixed another one I saw.
2013-07-22 11:34:10 -07:00
Dario Russi f2f631c163 IterInit, IterInitK, IterNet and IterNextK specializations and guards
Specialize IterInit and IterInitK after collection gurads and specialize IterNext and IterNextK after iter guard for collections and array
2013-07-22 11:34:10 -07:00
Jordan DeLong e28e3f205e Allow using ExtraData-supplied immediates in native-calls.cpp
Ports CreateCont* opcodes to use extra data for their
compile-time constants as a test case.
2013-07-22 11:34:10 -07:00
Jordan DeLong 6eaa0bb2f0 Verifier: always verify in debug builds
Let's prevent the verifier from bitrotting.
2013-07-22 11:34:09 -07:00
Edwin Smith 7204d561e5 Devirtualize ArrayData part 2
Convert remaining virtual methods to static methods dispatched
by kind.  This makes ArrayData a non-virtual class, so shuffle
fields and adjust static_asserts.
2013-07-22 11:34:09 -07:00
Edwin Smith 4f292ebb7f Fixed broken build from unused local variable.
that's it
2013-07-22 11:34:09 -07:00
Edwin Smith 49915fe2e6 Devirtualize ArrayData part 1
Moves about half of ArrayData virtual methods to g_array_funcs as
static functions instead of virtual functions.  This is mostly a
mechanical factor, except a handful of methods that are specialized
for Vector instead of generic HphpArray.
2013-07-22 11:34:09 -07:00
Sean Cannella acf4bf6487 Enable additional compiler warnings for gcc 4.7.1
Add compiler warnings to our build that are part of OSS to
catch them earlier.
2013-07-22 11:34:08 -07:00
Sean Cannella 739ffb3b24 OSX warnings (last batch to enable 4.7.1 warnings)
- fix last batch of warnings
2013-07-22 11:34:08 -07:00
Owen Yamauchi 68202e773c Delete GlobalCache
Pulling the trigger; it's unused post-tx64. This diff preserves the
ability to mark units as merge-only when the pseudomain only contains
assignments to known globals. When the unit is being merged, the set
operation goes directly to the global varenv instead of through the
targetcache (GlobalCache stored pointers into the global varenv's
NameValueTable).

Supersedes D891179 -- I was overly aggressive in that one.
2013-07-22 11:34:08 -07:00
Jan Oravec 7cd2bb8c42 Use Cell instead of TypedValue whenever possible
Most of the values stored in TypedValue in ext_asio are always Cells.
Let's use Cell type alias to improve code readability, pass them by
reference where null is not allowed and use Cell-specific functions
from tv_helpers.h.
2013-07-22 11:34:07 -07:00
Joel Marcey e6a11355a1 Implement PHP_BINARY PHP core predefined constant
Implement PHP_BINARY PHP core predefined constant. PHPUnit uses this constant in its self-test suite, causing many of them to fail on HHVM (possibly only because of the lack of this constant). Try to ninitially implement in such a way that it can be nimble enough for open-source, cross platform.
2013-07-22 11:34:07 -07:00
Joel Marcey b951f3b42d Implement json_last_error for PHPUnit
PHPUnit calls json_last_error. We need to implement it. Also implemented a simple json_last_error_msg to bring it up to 5.5 parity in that regard. This current implementation does not bring all the json zend tests to passing. But 2 out of the 22 bad tests now pass. And, this allows the PHPUnit self test to run as well.
2013-07-22 11:34:07 -07:00
Paul Bissonnette e9a9050451 OpDiv in codegen
added OpDiv to codegen if at least one operand is a double
2013-07-22 11:34:07 -07:00
Herman Venter 736f997ba8 Use PHP test framework for testing hphpd in sandbox server mode
Debugger tests that run hphp in non local mode (i.e. with the "-h some-server:some-port" option specified) currently use a clunky specialized C++ test harness that invokes PHP scripts that talk to the debugger client via the obsolete client API. This revision moves those tests to the new PHP only framework. The debugger client is now controlled by piping in commands, just like the other debugger tests. The main difference is that the debugger client is connected to a server instance and a separate PHP driver is used to load the server, load the client, and then load pages from the server so that the client can hit breakpoints. It also checks that the client can respond to ctrl-c by actually sending a SIGINT signal to the client process.
2013-07-22 11:34:06 -07:00
Paul Tarjan 53c7d78eea make socket test less flakey (hopefully)
I keep seeing problems with this test. Lets see if opening less sockets helps? The last few have failed on `socket_get_option($s, SOL_SOCKET, SO_TYPE)` which this does't fix though...
2013-07-22 11:34:06 -07:00
Guilherme Ottoni 0ae5908b61 Eliminate unconditional jump from main trace to exit trace before DCE
I ran into this problem with the region JIT.  Without this fix, an
IncRef may appear to be dead in the main trace during ref-counting
optimization (performed along with DCE).
2013-07-22 11:34:06 -07:00
Jan Oravec 87fa04b2f2 tv{Cell,Var}As*(TypedValue*) -> {cell,var}As*({Cell,Var}&)
Make tv{Cell,Var}As* take {Cell,Var} instead of TypedValue. Take them by
reference instead of by pointer.
2013-07-22 11:34:05 -07:00
Paul Tarjan 4e86ef19fc actually call o_toBoolean when casting to a bool - take 2
Redoing the diff. The original was breaking perflab, I want to see why (it worked for me, but without the `movb` change, maybe that was it).
2013-07-22 11:34:05 -07:00
mwilliams da5b2a2be2 Fix convenience test name matching
It used to lookup the longest initial sequence that contained
no slashes, so that eg:

  cd hphp/test
  ./run quick/SetM.php

Would run all the quick tests
2013-07-22 11:34:05 -07:00
Mike Magruder 4048565e87 Ensure flow control commands don't remove internal breakpoints set by real breakpoints
A real breakpoint makes entries in the breakpoint filter for all offsets at the given line. Various flow control commands will also use the breakpoint filter to add and remove temporary "internal breakpoints" required during the flow operation. Ensure that we never remove a breakpoint filter entry if there was already one there due to a breakpoint (or really  any other reason).
2013-07-22 11:34:05 -07:00
Mike Magruder 3231abf20a Add option to extend the time we'll wait before dropping into the dummy sandbox on debugger signals
When the proxy's signal polling thread gets a signal from the debugger client, it would normally wait one second for another thread to recognize and consume the signal. This is pretty reasonable, but with a debug build on a heavily loaded system it's very rarely possible for one second to not be long enough. Added a runtime option to extend this, and set it to 3s for the existing debugger server tests.
2013-07-22 11:34:04 -07:00
Sara Golemon 285b9e1d59 Add jemalloc and libintl include dirs to path
Remove bad defines for jemalloc on macosx
2013-07-20 08:44:51 -07:00
Sara Golemon 67a5b35892 Normalize newlines when doing expectf comparison in test/run
Newlines in expectf files don't necessarily match
newlines output by tests.  In the case of the bug55273 test,
the expectf file has unix (\n) newlines, but chunk_split()
produces DOS (\r\n) newlines by default.  This pattern
normalizes all expected newlines to accept unix, DOS, or old-style
Mac (\r) newlines.
2013-07-19 12:57:30 -07:00
Sara Golemon 65a6125580 Match PHP's numeric type conversion rules for math functions
Null/Bool/Object get converted to numeric values.
Touches abs(), floor(), ceil(), and round().
2013-07-19 12:57:30 -07:00
Sara Golemon 825cb52060 Fix parse_url()
Bug#54180 - Fragments containing '?'
Do not throw a notice on bad URLs
Add 'port' to return value after 'host', not at end of array
2013-07-19 12:57:29 -07:00
Paul Tarjan 38330353f6 warning on bad chdir
matches zend
2013-07-19 12:57:29 -07:00
Daniel Sloof cadddcd0d3 enable ServiceData on OSX
- re-enable servicedata on OSX now that jemalloc is fixed

Closes #865
2013-07-19 12:57:29 -07:00
Paul Bissonnette 1227cda52e Fixing bug with IterBreak assembler
Was failing to push iterator ID along with type in assembler.
2013-07-19 12:57:28 -07:00
Sean Cannella f319a3c029 gcc 4.7.1 unused-variable warnings
- fix unused variable warnings from OSS
2013-07-19 12:57:28 -07:00
mwilliams 76aed9f150 Empty loops need to check surprise flags
We didnt count a brach to itself as a backward branch.
Also, there seemed to be a signed vs unsigned issue with IterBreak.
2013-07-19 12:57:28 -07:00
Edwin Smith 1e3f2c2864 Remove checkExist option to ArrayData::lval()
It appears to be a leftover optimization that only applied to HPHPC,
which is gone now.
2013-07-19 12:57:27 -07:00
Guilherme Ottoni f107113ed3 Remove handling for const Bools that are neither 0 nor 1
It looks like whatever was introducing these has been fixed.
2013-07-19 12:57:27 -07:00
Bert Maher abca91e0fa Exit early during checkInvariants rather than do the O(N) loop.
This loop is useful for debugging arrays but is too slow for
general use, so we'll just "return true" before it and leave it in
place for offline use.
2013-07-19 12:57:27 -07:00
Owen Yamauchi 877c8ee9ec Minor cleanup of break/continue emission
Since variable break/continue is gone, we don't need this jonx anymore,
since the target of any break or continue is statically known. The
regular break/continue handling deals with this case appropriately.
2013-07-19 12:57:26 -07:00
Edwin Smith 353b33928b Make ArrayKind a regular enum
We use ArrayKind as a simple unsigned integer, its an index, we do
range-based comparisons, and in the future we'll likely do bit-ops
for fast sub-kind tests.  Just be honest that this is an old-school enum.
2013-07-19 12:57:26 -07:00
Sara Golemon 26a024296d Travis configure script need to have an up to date package list 2013-07-18 17:42:52 -07:00
Daniel Sloof c494c3a145 Don't use "echo -n" in /bin/sh scripts on MacOSX
The shell builtin implementation of echo on MacOSX
doesn't respect the -n flag.  This is the only usage of it
in our stack so far and we can avoid it by hiding the generated
token from the linter in a different way.
2013-07-18 17:28:44 -07:00
danslo 079dc468ca Comments are not SimpleXML element children
- Comments should not be counted as node children

Closes #863
2013-07-18 17:28:44 -07:00
Sean Cannella e5fc6d56f4 Document known limitation with PHP setlocale()
- Github contributor @karpa13a found and requested this issue be documented

Closes #860
2013-07-18 17:28:44 -07:00
Sean Cannella db987b4a4d clean up gcc 4.7.1 warnings on OSX
- cleans up new warnings
2013-07-18 17:28:43 -07:00
Edwin Smith 608df352de HphpArray Vector specializations
Introduces a new m_kind for vector-shaped HphpArray instances.
A vector has integer indexes in the range [0..size), and no
tombstones.  Internally it does not store the integer keys or
hashtable, although this version still allocates space for it.
2013-07-18 17:28:43 -07:00
Paul Tarjan 0335e335b7 build setAccessible
This implementation feels a bit haphazard with all the forces in the `o_*`. Is this stuff all changing dario?
2013-07-18 17:28:42 -07:00
Mirek Klimos 90b7170582 Remove Continuation from local 0
No emitted bytecode relies on Continuation being stored in local 0
anymore. Stop using local 0 for this purpose and compute offset
to the Continuation at JIT time. 16 bytes of memory freed.

At this point all locals of Continuation construction wrapper share the
same indices with their respective locals of Continuation body, which
should allow further optimizations.
2013-07-18 17:28:42 -07:00
Mirek Klimos f11bab46b7 Eliminate Continuation in local 0: JIT
The the code is being translated, we statically know offset of
Continuaton from its ActRec. Use this knowledge to emit data fetches
relative to ActRec rather than relative to Continuation loaded from
local 0.
2013-07-18 17:28:42 -07:00
huzhiguang 506329b7ce error_log add message_type=3 function
add f_error_log message_type=3 function
hhvm defult error_log message_type 0,so it can't support user-defind error_log mode(message_type=3)

Closes #831

Github: https://github.com/facebook/hiphop-php/pull/831
2013-07-18 17:28:41 -07:00
bsimmers 4665b068d4 Initial tracelet region selector
This diff renames the Tracelet -> RegionDesc conversion mode to
"legacy" (since it's going away eventually) and changes "tracelet" to use the
new region selection mode. It attempts to select a region that will be the same
length as what Translator::analyze would come up with, using HhbcTranslator for
all of the type flow logic. It generates longer tracelets in some cases due to
more precise type information. Once this new mode is no longer a perf
regression it can become the new default, replacing all the code in
Translator::analyze and the "legacy" region mode. This version doesn't support
inlining or tracking of known Func*s; those will come in later diffs.
2013-07-18 17:28:41 -07:00
Paul Tarjan c9b0ebd674 change get_resource_type() to match zend
in composer.phar they test `get_resource_type` and make sure it matches this string. This just seemed like a bug.
2013-07-18 17:28:40 -07:00
Paul Tarjan 22f908f1d7 add some more constants that zend defines
`composer.phar` was using these, so we should probably define them. I made them match what we were giving for `PHP_VERSION`.
2013-07-18 17:28:40 -07:00
Mike Magruder 601ca57f53 Cleanup debugger client shutdown
The exit path for the debugger client has always been a little odd. We'd call a shutdown function which would destroy the client, then later call a stop function which would first make a new client, then stop it, then that one would get destroyed later. Made it so we stop and destroy just one client.
2013-07-18 17:28:40 -07:00
Herman Venter ee2cd8d32e Do not evaluate breakpoint conditions during stepping.
Flow control commands should not evaluate the conditions of conditional breakpoints when enabling and disabling breakpoints during stepping. Also, all breakpoints, rather than just the first matching breakpoint should be enabled/disabled.
2013-07-18 17:28:39 -07:00
Jordan DeLong 29dbaf3ae9 Remove assert on maxStackCells > 0
One of these was left over.
2013-07-18 17:28:39 -07:00
Mike Magruder 76fd23c2cb Remove rare flakieness from protocol tests
There was a race in the debugger protocol tests which send bad commands to the proxy and expect it to disconnect. If the proxy thread was fast enough it would mark the client as stopped, and we'd skip trying to get a new message after sending the bad command. This means missing one line of output in very rare cases. I've put in a wait to ensure that the client settles in the stopped state before continuing, to remove the race.
2013-07-18 17:28:39 -07:00
Owen Yamauchi 86eb82ec2f Fix break/continue parsing
This is exactly what Zend's parser does now. I'm a little sad about
adding the bool parameter, but all the checking code was exactly
duplicated otherwise, and that seemed like the worse alternative.

Fixes #854
2013-07-18 17:28:38 -07:00
mwilliams db130c83e1 Identify direct children of yield expressions
We want to be able to recognize them without knowing their
context.
2013-07-18 17:28:38 -07:00
Paul Bissonnette 0a111314bd Adding shift left and right to codegen
shift left and right in codegen
2013-07-18 17:28:37 -07:00
Kyle Delong a8e3321fbd HPHP/XHP: 'mixed' type in attribute declarations
We'd like to start using ##mixed## instead of ##var## for attribute types to be consistent with Hack. As a followup to this (once released), we would codemod all ##var## to ##mixed##.
2013-07-18 17:28:37 -07:00
Mike Magruder f3d5a8abb1 Allow ctrl-c during eval
A client couldn't break execution during eval. There used to be a lot of barriers to making that right, but I fixed most of them with a previous diff on unifying client-side event loops. Now the only barrier was that a server-side thread processing an interrupt was blocking the signal polling thread by holding a mutex while processing the interrupt. Changed to set a flag to disable polling when starting to process the interrupt (and unsetting it when done), while still synchronizing with the signal polling thread to ensure only one thread is sending the client messages at a time. Added logic to re-enable polling while executing PHP for eval, print, etc. Plumbed the proxy thru to the point where we check the clause on conditional breakpoints, too, since that's the third (and final) place we do this.
2013-07-18 17:28:36 -07:00
Herman Venter b03f72d185 Only one break point can be set per file when running against a server
When the client sends a list of breakpoints over to the server, the logic that applies the breakpoints as soon as a file is loaded is broken. It stops looking at breakpoints as soon as it finds the first one. It should carry on and look at all of them.
2013-07-18 17:28:36 -07:00
Edwin Smith 721f89b890 Flatten directories under runtime/base
This moves runtime/base/*/* to runtime/base, and fixes paths.
2013-07-18 17:28:35 -07:00
bsimmers a9e58686ab Pull Translator's translate* methods into a separate class
This diff creates IRTranslator, which creates and uses an
HhbcTranslator to implement the translate* methods. It can be used
independently of Translator or TranslatorX64 (it isn't yet but my next
region compiler diff uses it). I also moved a bunch of methods out of
inappropriate classes and changed the type guard/assert methods in
HhbcTranslator to use RegionDesc::Location instead of Transl::Location
and fixes a local tracking issue in translateRegion.
2013-07-18 17:28:34 -07:00
Jordan DeLong 43d8497245 Translate BitNot on doubles 2013-07-18 17:28:34 -07:00
Benjamin Strahs 8ce9231f1b Fix DOMDocument UTF-16 parsing
We should be using xmlCreateMemoryParserCtxt for in-memory XML documents because it correctly handles UTF-16 encoded strings.
2013-07-18 17:28:33 -07:00
Owen Yamauchi 4cea6506e6 Get rid of NameValueTableWrapper, part 2 of 3
Part 2: getting rid of NVTW for initializing nonscalar static
properties. This is slightly messier than the equivalent for nonstatic
properties.
2013-07-18 17:28:33 -07:00
Sara Golemon 96151050af Update folly 2013-07-18 17:28:32 -07:00
Sara Golemon 5c93a5fe40 Prevent buffer overrun during iopBitOr on string args
"foo" | "f" is meant to yield a string of length
max(strlen("foo"), strlen("f")) by bitwise ORing each byte
of one string against the corresponding byte of the other.

When the strings are of differing lengths, however, we get unknown
garbage data from past the end of the buffer.  This data is
often '\0', however under memory pressure we can get any
value and the behavior becomes undefined.
2013-07-18 17:28:22 -07:00
Keith Adams bbcf1a2db3 Make Asm::code private.
Having everybody and their uncle reading and writing fields out
of a.code and stubs.code was making assembler work hard. This replaces most
reads with accessors, and all writes with structured friends of
X64SAssembler.
2013-07-15 18:13:31 -07:00
Edwin Smith c4e406b62f Move runtime/base/server to runtime/server
This is an incremental step towards moving it all the way
to hphp/server.  This flattens base but doesn't untangle
the server files from lib_hphp_runtime
2013-07-15 18:13:25 -07:00
Keith Adams d3673cad74 Make it possible to wait for gdb on crash.
Often I happen not to be running under a debugger when a
crash occurs. In my debugging workflow, I'd prefer our crash handler to
preserve the broken state and spin waiting for gdb to attach rather than
dump core, attempt its own little sad stacktraces, etc. Driven via a
default-false config flag.
2013-07-15 17:35:33 -07:00
Mike Magruder f3e19a5dfa Fix machine force attach
I broke the operation of CmdMachine when we attach with the force flag with https://phabricator.fb.com/D851880. I consolidated some error handling logic around broken connections, etc., and in particular pulled throwing of an exception into forceQuit(). I failed to realize there was a single call site of forceQuit() that did not in fact throw an exception afterwards… the logic underneath of force attach. Switching the forceQuit() call there to stop() replaces the logic that was there previously, and restores the behavior.
2013-07-15 17:35:32 -07:00
aravind b5f608b942 always_assert when we run out of TC space
Makes debugging easier.
2013-07-15 17:35:32 -07:00
Herman Venter 10f93d4828 Do not report start, end and psp breakpoints as unbound when connected to a sandbox.
break start/end/psp currently always report themselves as unbound. If the client is connected to a sanbox, these should instead be treated as bound. Also, break clear all currently removes breakpoints without running their destructors in the right order, which causes the break point counter to not reset to 1.
2013-07-15 17:35:31 -07:00
Daniel Sloof 9904554f66 fix issue with finding embedded systemlib on OSX
- make finding embedded systemlib data path independent on OSX
2013-07-15 17:35:27 -07:00
Mike Magruder f051e2fe04 Don't go back to the interpreter after the end of pseudo main when debugging
Fix a long-standing bug where if you step off of the end of pseudo main we'd segfault in the interpreter loop. To get this we have to have a breakpoint in the final TC in pseudo main, and have that called from another TC, then Step or Next off the end. We'd end up with a PC of zero after the ret, which makes sense, but the logic after interpreting a block of code to stay in the interpreter when debugging was blind to this case.
2013-07-15 17:34:47 -07:00
Edwin Smith 9b6bf426b9 Move runtime/base/array/* up one level.
Also rename array_inline.h to array_data-inl.h
2013-07-15 17:34:47 -07:00
Sean Cannella 7d07873817 OSX warnings
- fix OSS warnings
2013-07-15 17:34:42 -07:00
Joel Marcey ffab2c17f8 Implement SplObjectStorage::getInfo()
Implement SplObjectStorage::getInfo(). PHPUnit requires this method.
2013-07-15 15:46:32 -07:00
Sanjeev Singh 75397a10c7 Initial rough draft of xhpast2, a replacement for xhpast
The goal of this diff is to clean up the current work-in-progress and check
it in so that others may contribute if they have time.

The program currently outputs the HHVM tree as well as the xhpast-like
json, for ease of debugging. There is a little helper program jsonpretty.py
to make the trees more readable, e.g.

_build/dbg/hphp/util/parser/xhpast/xhpast2 <some php file> | hphp/util/parser/xhpast/xhpast2/jsonpretty.py
2013-07-15 15:46:32 -07:00
Edwin Smith 746862246f Fix typos from "Remove do/while(0) trick in iopFCallBuiltin macros"
s/-1/-i/
Add missing \
2013-07-15 15:46:28 -07:00
Jordan DeLong a28b21c191 Remove do/while(0) trick in iopFCallBuiltin macros
It doesn't really make sense in this context.  Also pushed
the if statement down into the CASE macro for now and fixed some
indentation.
2013-07-15 15:46:28 -07:00
Jordan DeLong 0c489492dc Remove array_iter_foo functions from Variant and VRefParam @override-unit-failures
Pretty much just moves them to their only callers in
ext_array.
2013-07-15 15:46:27 -07:00
Jordan DeLong 8e3ee5a87f Use stringToNumeric in tv_comparisons
I like this api slightly better than passing in multiple
output refs, but when I added I didn't change these so I could see
perflabs separately.
2013-07-15 15:46:27 -07:00
Jordan DeLong 1c764cabf0 Remove redundant function in Array
get() and getArrayData() do the same thing.
2013-07-15 15:46:27 -07:00
34121 arquivos alterados com 1355039 adições e 354584 exclusões
+6 -17
Ver Arquivo
@@ -1,10 +1,5 @@
*.[oad]
*.hhbc
/bin*-g
/bin*-O
/bin/*.so
/bin/hphp_options
/bin/systemlib.php
.mkdir
hphp.log
@@ -31,18 +26,14 @@ hphp.log
/hphp/runtime/tmp/run
/hphp/runtime/tmp/run.sh
/hphp/runtime/tmp/libtest.so
/hphp/hphp_build_info.cpp
/hphp/hphp_repo_schema.h
/hphp/hphp-build-info.cpp
/hphp/hphp-repo-schema.h
/hphp/hhvm/gen
/hphp/hhvm/hhvm
/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/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
@@ -51,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
@@ -64,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
+42 -7
Ver Arquivo
@@ -1,13 +1,48 @@
language: cpp
compiler:
- gcc
before_script:
- ./configure_ubuntu_12.04.sh
# for some tests
- sudo locale-gen de_DE && sudo locale-gen zh_CN.utf8 && sudo locale-gen fr_FR
- HPHP_HOME=`pwd` make -j 8
script: hphp/hhvm/hhvm hphp/test/run quick slow zend
before_script:
- time TRAVIS=1 ./configure_ubuntu_12.04.sh
# for some tests
- time sudo locale-gen de_DE && sudo locale-gen zh_CN.utf8 && sudo locale-gen fr_FR
- time HPHP_HOME=`pwd` make -j 6
- cd hphp/test/zend/good/ext/curl/tests/responder && ../../../../../../../hhvm/hhvm -m server -p 8444 &
# 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=""
# The larger test suites (slow, zend) take longer than 50 miuntes to run. Since
# we have no way to change the timeout, we subdivide the jit/interp repo/normal
# matrix and then further split the large suites using an experimental cut
# which divides the number of tests in each sub-run roughly in two.
env:
- TEST_RUN_MODE="-m jit quick"
- TEST_RUN_MODE="-m jit slow -I /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m jit slow -E /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m jit zend -I /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m jit zend -E /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/'
- TEST_RUN_MODE="-m jit -r quick"
- TEST_RUN_MODE="-m jit -r slow -I /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m jit -r slow -E /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m jit -r zend -I /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m jit -r zend -E /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m interp quick"
- TEST_RUN_MODE="-m interp slow -I /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m interp slow -E /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m interp zend -I /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m interp zend -E /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m interp -r quick"
- TEST_RUN_MODE="-m interp -r slow -I /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m interp -r slow -E /^hphp\/test\/slow\/[a-df-nw-x].*/"
- TEST_RUN_MODE="-m interp -r zend -I /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
- TEST_RUN_MODE="-m interp -r zend -E /^hphp\/test\/zend\/good\/(ext\/[a-ru-zA-Z0-9]|[Z]).*/"
script: time PHP_CURL_HTTP_REMOTE_SERVER="http://localhost:8444" 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()
+13
Ver Arquivo
@@ -0,0 +1,13 @@
if (EDITLINE_LIBRARIES AND EDITLINE_INCLUDE_DIRS)
set (Editline_FIND_QUIETLY TRUE)
endif (EDITLINE_LIBRARIES AND EDITLINE_INCLUDE_DIRS)
find_path(EDITLINE_INCLUDE_DIRS NAMES editline/readline.h)
find_library(EDITLINE_LIBRARIES NAMES edit)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Editline DEFAULT_MSG
EDITLINE_LIBRARIES
EDITLINE_INCLUDE_DIRS)
mark_as_advanced(EDITLINE_INCLUDE_DIRS EDITLINE_LIBRARIES)
+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
)
+27
Ver Arquivo
@@ -0,0 +1,27 @@
# - Try to find libdl
# Once done this will define
#
# LIBDL_FOUND - system has libdl
# LIBDL_INCLUDE_DIRS - the libdl include directory
# LIBDL_LIBRARIES - Link these to use libdl
# LIBDL_NEEDS_UNDERSCORE - If extern "C" symbols are prefixed (BSD/Apple)
#
find_path (LIBDL_INCLUDE_DIRS NAMES dlfcn.h)
find_library (LIBDL_LIBRARIES NAMES dl)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDL DEFAULT_MSG
LIBDL_LIBRARIES
LIBDL_INCLUDE_DIRS)
SET(CMAKE_REQUIRED_LIBRARIES dl)
INCLUDE(CheckCSourceRuns)
CHECK_C_SOURCE_RUNS("#include <dlfcn.h>
void testfunc() {}
int main() {
testfunc();
return dyslm(0, \"_testfunc\") != (void*)0;
}" LIBDL_NEEDS_UNDERSCORE)
mark_as_advanced(LIBDL_INCLUDE_DIRS LIBDL_LIBRARIES LIBDL_NEEDS_UNDERSCORE)
+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)
+13
Ver Arquivo
@@ -0,0 +1,13 @@
if (LIBNUMA_LIBRARIES AND LIBNUMA_INCLUDE_DIRS)
set (LibNuma_FIND_QUIETLY TRUE)
endif (LIBNUMA_LIBRARIES AND LIBNUMA_INCLUDE_DIRS)
find_path(LIBNUMA_INCLUDE_DIRS NAMES numa.h)
find_library(LIBNUMA_LIBRARIES NAMES numa)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibNuma DEFAULT_MSG
LIBNUMA_LIBRARIES
LIBNUMA_INCLUDE_DIRS)
mark_as_advanced(LIBNUMA_INCLUDE_DIRS LIBNUMA_LIBRARIES)
+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
@@ -1,28 +0,0 @@
#
# $Id$
#
# - Find libunwind
# Find libunwind
#
# LIBUNWIND_INCLUDE_DIR - where to find unwind.h and libunwind.h
# LIBUNWIND_LIBRARY - List of libraries when using libunwind
# LIBUNWIND_FOUND - True if libunwind found.
if(LIBUNWIND_INCLUDE_DIR)
# Already in cache, be silent
SET(LIBUNWIND_FIND_QUIETLY TRUE)
endif()
FIND_PATH(LIBUNWIND_INCLUDE_DIR libunwind.h)
if(NOT EXISTS "${LIBUNWIND_INCLUDE_DIR}/unwind.h")
message(FATAL_ERROR "libunwind.h found without matching unwind.h")
SET(LIBUNWIND_INCLUDE_DIR "")
endif()
FIND_LIBRARY(LIBUNWIND_LIBRARY unwind)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBUNWIND DEFAULT_MSG LIBUNWIND_LIBRARY LIBUNWIND_INCLUDE_DIR)
MARK_AS_ADVANCED(LIBUNWIND_LIBRARY LIBUNWIND_INCLUDE_DIR)
+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()
+56
Ver Arquivo
@@ -0,0 +1,56 @@
if(CMAKE_COMPILER_IS_GNUCC)
INCLUDE(CheckCSourceCompiles)
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40700
#error Not GCC 4.7.0+
#endif
int main() { return 0; }" HAVE_GCC_47)
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+
#endif
int main() { return 0; }" HAVE_GCC_48)
endif()
set(FREEBSD FALSE)
set(LINUX FALSE)
if("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
set(FREEBSD TRUE)
endif()
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
set(LINUX TRUE)
endif()
if($ENV{CXX} MATCHES "icpc")
set(CMAKE_C_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -w")
set(CMAKE_CXX_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -fno-omit-frame-pointer -ftemplate-depth-180 -Wall -Woverloaded-virtual -Wno-deprecated -w1 -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names")
else()
set(GNUCC_48_OPT "")
if(HAVE_GCC_48)
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-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)
set(CMAKE_C_FLAGS_RELEASE "-O3")
endif()
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS_RELEASE "-O3")
endif()
+133 -43
Ver Arquivo
@@ -17,10 +17,25 @@
include(CheckFunctionExists)
# libdl
find_package(LibDL)
if (LIBDL_INCLUDE_DIRS)
add_definitions("-DHAVE_LIBDL")
include_directories(${LIBDL_INCLUDE_DIRS})
if (LIBDL_NEEDS_UNDERSCORE)
add_definitions("-DLIBDL_NEEDS_UNDERSCORE")
endif()
endif()
# boost checks
find_package(Boost 1.48.0 COMPONENTS system program_options filesystem regex REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
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)
@@ -38,10 +53,6 @@ if (LIBINOTIFY_INCLUDE_DIR)
include_directories(${LIBINOTIFY_INCLUDE_DIR})
endif()
# unwind checks
find_package(Libunwind REQUIRED)
include_directories(${LIBUNWIND_INCLUDE_DIR})
# iconv checks
find_package(Libiconv REQUIRED)
include_directories(${LIBICONV_INCLUDE_DIR})
@@ -79,29 +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 ()
if (WANT_FB_LIBMCC)
add_definitions(-DHPHP_WITH_LIBMCC)
message(FATAL_ERROR Need to add libmcc and libch for linking)
else ()
# nothing for now
# 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
@@ -137,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)
@@ -150,9 +179,6 @@ if (ICU_FOUND)
include_directories(${ICU_INCLUDE_DIRS})
endif (ICU_FOUND)
# (google heap OR cpu profiler) AND libunwind
FIND_LIBRARY(UNWIND_LIB unwind)
# jemalloc/tmalloc and profiler
if (USE_GOOGLE_HEAP_PROFILER OR USE_GOOGLE_CPU_PROFILER)
FIND_LIBRARY(GOOGLE_PROFILER_LIB profiler)
@@ -178,10 +204,30 @@ if (USE_GOOGLE_HEAP_PROFILER AND GOOGLE_PROFILER_LIB)
endif()
if (USE_JEMALLOC AND NOT GOOGLE_TCMALLOC_ENABLED)
FIND_LIBRARY(JEMALLOC_LIB jemalloc)
if (JEMALLOC_LIB)
message(STATUS "Found jemalloc: ${JEMALLOC_LIB}")
set(JEMALLOC_ENABLED 1)
FIND_LIBRARY(JEMALLOC_LIB NAMES jemalloc)
FIND_PATH(JEMALLOC_INCLUDE_DIR NAMES jemalloc/jemalloc.h)
if (JEMALLOC_INCLUDE_DIR AND JEMALLOC_LIB)
include_directories(${JEMALLOC_INCLUDE_DIR})
set (CMAKE_REQUIRED_INCLUDES ${JEMALLOC_INCLUDE_DIR})
INCLUDE(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("
#include <jemalloc/jemalloc.h>
int main(void) {
#if !defined(JEMALLOC_VERSION_MAJOR) || (JEMALLOC_VERSION_MAJOR < 3)
# error \"jemalloc version >= 3.0.0 required\"
#endif
return 0;
}" JEMALLOC_VERSION_3)
set (CMAKE_REQUIRED_INCLUDES)
if (JEMALLOC_VERSION_3)
message(STATUS "Found jemalloc: ${JEMALLOC_LIB}")
set(JEMALLOC_ENABLED 1)
else()
message(STATUS "Found jemalloc, but it was too old")
endif()
endif()
endif()
@@ -197,9 +243,6 @@ endif()
if (JEMALLOC_ENABLED)
add_definitions(-DUSE_JEMALLOC=1)
if (APPLE)
add_definitions(-DJEMALLOC_MANGLE=1 -DJEMALLOC_EXPERIMENTAL=1)
endif()
else()
add_definitions(-DNO_JEMALLOC=1)
endif()
@@ -259,14 +302,26 @@ include_directories(${NCURSES_INCLUDE_PATH})
find_package(PThread REQUIRED)
include_directories(${LIBPTHREAD_INCLUDE_DIRS})
find_package(Readline REQUIRED)
include_directories(${READLINE_INCLUDE_DIR})
# Either Readline or Editline (for hphpd)
find_package(Readline)
find_package(Editline)
if (READLINE_INCLUDE_DIR)
include_directories(${READLINE_INCLUDE_DIR})
elseif (EDITLINE_INCLUDE_DIRS)
add_definitions("-DUSE_EDITLINE")
include_directories(${EDITLINE_INCLUDE_DIRS})
else()
message(FATAL_ERROR "Could not find Readline or Editline")
endif()
find_package(CClient REQUIRED)
include_directories(${CCLIENT_INCLUDE_PATH})
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})
@@ -280,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)
@@ -335,6 +399,9 @@ endif()
if (APPLE)
find_library(LIBINTL_LIBRARIES NAMES intl libintl)
if (LIBINTL_INCLUDE_DIR)
include_directories(${LIBINTL_INCLUDE_DIR})
endif()
find_library(KERBEROS_LIB NAMES gssapi_krb5)
endif()
@@ -349,6 +416,10 @@ include_directories(${HPHP_HOME}/hphp)
include_directories(${HPHP_HOME}/hphp/system/gen)
macro(hphp_link target)
if (LIBDL_LIBRARIES)
target_link_libraries(${target} ${LIBDL_LIBRARIES})
endif ()
if (GOOGLE_HEAP_PROFILER_ENABLED OR GOOGLE_CPU_PROFILER_ENABLED)
target_link_libraries(${target} ${GOOGLE_PROFILER_LIB})
endif()
@@ -364,7 +435,6 @@ macro(hphp_link target)
endif()
target_link_libraries(${target} ${Boost_LIBRARIES})
target_link_libraries(${target} ${LIBUNWIND_LIBRARY})
target_link_libraries(${target} ${MYSQL_CLIENT_LIBS})
target_link_libraries(${target} ${PCRE_LIBRARY})
target_link_libraries(${target} ${ICU_DATA_LIBRARIES} ${ICU_I18N_LIBRARIES} ${ICU_LIBRARIES})
@@ -418,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})
@@ -434,15 +518,21 @@ 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)
target_link_libraries(${target} ${READLINE_LIBRARY})
if (READLINE_LIBRARY)
target_link_libraries(${target} ${READLINE_LIBRARY})
elseif (EDITLINE_LIBRARIES)
target_link_libraries(${target} ${EDITLINE_LIBRARIES})
endif()
target_link_libraries(${target} ${NCURSES_LIBRARY})
target_link_libraries(${target} ${CCLIENT_LIBRARY})
if (CCLIENT_NEEDS_PAM)
if (PAM_LIBRARY)
target_link_libraries(${target} ${PAM_LIBRARY})
endif()
+78
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)
@@ -67,3 +88,60 @@ macro(MYSQL_SOCKET_SEARCH)
set(MYSQL_UNIX_SOCK_ADDR ${MYSQL_SOCK} CACHE STRING "Path to MySQL Socket")
endif()
endmacro()
function(embed_systemlib TARGET DEST SOURCE SECTNAME)
if (APPLE)
target_link_libraries(${TARGET} -Wl,-sectcreate,__text,${SECTNAME},${SOURCE})
else()
add_custom_command(TARGET ${TARGET} POST_BUILD
COMMAND "objcopy"
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})
set_target_properties(${EXTNAME} PROPERTIES PREFIX "")
set_target_properties(${EXTNAME} PROPERTIES SUFFIX ".so")
endfunction()
function(HHVM_SYSTEMLIB EXTNAME SOURCE_FILE)
embed_systemlib(${EXTNAME} "${EXTNAME}.so" ${SOURCE_FILE} systemlib)
endfunction()
+49 -61
Ver Arquivo
@@ -1,5 +1,37 @@
include(Options)
# 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(ENABLE_FASTCGI 1)
set(HHVM_ANCHOR_SYMS -Wl,-uregister_libevent_server,-uregister_fastcgi_server)
endif()
set(HHVM_LINK_LIBRARIES
hphp_analysis
hphp_runtime_static
ext_hhvm_static
hphp_system
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()
@@ -8,29 +40,13 @@ IF(NOT DEFINED CMAKE_PREFIX_PATH)
message(STATUS "CMAKE_PREFIX_PATH was missing, proceeding anyway")
endif()
if(CMAKE_COMPILER_IS_GNUCC)
INCLUDE(CheckCSourceCompiles)
CHECK_C_SOURCE_COMPILES("#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40600
#error Need GCC 4.6.0+
#endif
int main() { return 0; }" HAVE_GCC_46)
if(NOT HAVE_GCC_46)
message(FATAL_ERROR "Need at least GCC 4.6")
endif()
endif()
set(FREEBSD FALSE)
set(LINUX FALSE)
if("${CMAKE_SYSTEM_NAME}" STREQUAL "FreeBSD")
set(FREEBSD TRUE)
endif()
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
set(LINUX TRUE)
# Look for the chrpath tool so we can warn if it's not there
find_program(CHRPATH chrpath)
IF (CHRPATH STREQUAL "CHRPATH-NOTFOUND")
SET(FOUND_CHRPATH OFF)
message(WARNING "chrpath not found, rpath will not be stripped from installed binaries")
else()
SET(FOUND_CHRPATH ON)
endif()
LIST(APPEND CMAKE_PREFIX_PATH "$ENV{CMAKE_PREFIX_PATH}")
@@ -42,11 +58,11 @@ if(APPLE)
endif()
endif()
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)
@@ -61,22 +77,6 @@ else()
message("Generating DEBUG build")
endif()
if(INFINITE_LOOP_DETECTION)
add_definitions(-DINFINITE_LOOP_DETECTION=1)
endif()
if(INFINITE_RECURSION_DETECTION)
add_definitions(-DINFINITE_RECURSION_DETECTION=1)
endif()
if(REQUEST_TIMEOUT_DETECTION)
add_definitions(-DREQUEST_TIMEOUT_DETECTION=1)
endif()
if(ENABLE_LATE_STATIC_BINDING)
add_definitions(-DENABLE_LATE_STATIC_BINDING=1)
endif()
if(DEBUG_MEMORY_LEAK)
add_definitions(-DDEBUG_MEMORY_LEAK=1)
endif()
@@ -93,10 +93,6 @@ if(HOTPROFILER)
add_definitions(-DHOTPROFILER=1)
endif()
if(HOTPROFILER_NO_BUILTIN)
add_definitions(-DHOTPROFILER_NO_BUILTIN=1)
endif()
if(EXECUTION_PROFILER)
add_definitions(-DEXECUTION_PROFILER=1)
endif()
@@ -123,28 +119,20 @@ 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)
# later versions of binutils don't play well without automake
add_definitions(-DPACKAGE=hhvm -DPACKAGE_VERSION=Release)
IF($ENV{CXX} MATCHES "icpc")
set(CMAKE_C_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -w")
set(CMAKE_CXX_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -w1 -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names")
else()
set(CMAKE_C_FLAGS "-w")
set(CMAKE_CXX_FLAGS "-fno-gcse -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names -Wno-error=array-bounds -Wno-error=switch -std=gnu++0x -Werror=format-security -Wno-unused-result -Wno-sign-compare")
endif()
IF(CMAKE_COMPILER_IS_GNUCC)
SET (CMAKE_C_FLAGS_RELEASE "-O3")
ENDIF()
IF(CMAKE_COMPILER_IS_GNUCXX)
SET (CMAKE_CXX_FLAGS_RELEASE "-O3")
ENDIF()
include_directories(${HPHP_HOME}/hphp)
include_directories(${HPHP_HOME}/hphp/lib/system/gen)
include_directories(${HPHP_HOME})
+3 -9
Ver Arquivo
@@ -1,24 +1,18 @@
#set(CMAKE_BUILD_TYPE Debug)
option(ENABLE_LATE_STATIC_BINDING "Enable Late Static Binding" ON)
option(INFINITE_LOOP_DETECTION "Enable Infinite Loop Detection" ON)
option(INFINITE_RECURSION_DETECTION "Enable Infinite Recursion Detection" ON)
option(REQUEST_TIMEOUT_DETECTION "Enable Timeout Detection" ON)
option(ALWAYS_ASSERT "Enabled asserts in a release build" OFF)
option(DEBUG_MEMORY_LEAK "Allow easier debugging of memory leaks" OFF)
option(DEBUG_APC_LEAK "Allow easier debugging of apc leaks" OFF)
option(HOTPROFILER "Enable support for the hot-profiler" OFF)
option(HOTPROFILER_NO_BUILTIN "Don't consider builtins for the hot-profiler" OFF)
option(EXECUTION_PROFILER "Enable the execution profiler" OFF)
option(ENABLE_FULL_SETLINE "Enable full setline function for debugger and code-coverage" OFF)
option(WANT_FB_LIBMCC "want FB Memcache" OFF)
option(USE_JEMALLOC "Use jemalloc" ON)
option(USE_TCMALLOC "Use tcmalloc (if jemalloc is not used)" ON)
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()
+18
Ver Arquivo
@@ -0,0 +1,18 @@
# Contributing to HipHop
We'd love to have your help in making HipHop better. If you run into problems, please open an [issue](http://github.com/facebook/hiphop-php/issues), or better yet, fork us and send a pull request.
If you want to help but don't know where to start, try fixing some of the [Zend tests that don't pass](hphp/test/zend/bad). You can run them with [hphp/test/run](hphp/test/run). When they work, move them to [zend/good](hphp/test/zend/good) and send a pull request.
All the open issues tagged [Zend incompatibility](https://github.com/facebook/hiphop-php/issues?labels=zend+incompatibility&page=1&state=open) are real issues reported by the community in existing PHP code and [frameworks](https://github.com/facebook/hiphop-php/wiki/OSS-PHP-Frameworks-Unit-Testing:-General) that could use some attention.
## Submitting Pull Requests
Before changes can be accepted a [Contributor Licensing Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hiphop-php/raw/master/hphp/doc/FB_Individual_CLA.pdf) - print, sign, scan, link) must be signed.
Please add appropriate test cases as you make changes; see [here](hphp/test) for more information. Travis-CI is integrated with this GitHub project and will provide test results automatically on all pulls.
## Additional Resources
* IRC:[#hhvm on freenode](http://webchat.freenode.net/?channels=hhvm)
* [Issue tracker](http://github.com/facebook/hiphop-php/issues)
+23 -10
Ver Arquivo
@@ -1,33 +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/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. If you run into problems, please open an [issue](http://github.com/facebook/hiphop-php/issues), or better yet, fork us and send a pull request. Join us on [#hhvm on freenode](http://webchat.freenode.net/?channels=hhvm).
We'd love to have your help in making HHVM better.
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/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.
Before changes can be accepted a [Contributors Licensing Agreement](http://developers.facebook.com/opensource/cla) ([pdf](https://github.com/facebook/hiphop-php/raw/master/hphp/doc/FB_Individual_CLA.pdf) - print, sign, scan, link) must be signed.
All the open issues tagged [Zend incompatibility](https://github.com/facebook/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.
## Licence
HipHop VM is licensed under the PHP and Zend licenses except as otherwise noted.
## License
HHVM is licensed under the PHP and Zend licenses except as otherwise noted.
## Reporting Crashes
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
+71 -16
Ver Arquivo
@@ -1,6 +1,6 @@
#########################################
#
# Install all the dependancies for HipHop
# Install all the dependencies for HipHop
#
#########################################
@@ -11,52 +11,107 @@ if [ "$0" != "$SCRIPT_NAME" ]; then
exit 1
fi
export CMAKE_PREFIX_PATH=`/bin/pwd`/..
export HPHP_HOME=`/bin/pwd`
if [ "x${TRAVIS}" != "x" ]; then
# Collect some stats for use in tuning build later on
free
CPUS=`cat /proc/cpuinfo | grep -E '^processor' | tail -1 | cut -d : -f 2`
CPUS=`expr ${CPUS} + 1`
echo "CPUs: ${CPUS}"
fi
sudo apt-get install git-core cmake g++ libboost1.48-dev libmysqlclient-dev \
export CMAKE_PREFIX_PATH=`/bin/pwd`/..
# 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 -y update
sudo apt-get -y install apt-fast
# install the actual dependencies
sudo apt-fast -y update
sudo apt-fast -y install git-core cmake g++ libboost1.48-dev libmysqlclient-dev \
libxml2-dev libmcrypt-dev libicu-dev openssl build-essential binutils-dev \
libcap-dev libgd2-xpm-dev zlib1g-dev libtbb-dev libonig-dev libpcre3-dev \
autoconf libtool libcurl4-openssl-dev libboost-regex1.48-dev libboost-system1.48-dev \
libboost-program-options1.48-dev libboost-filesystem1.48-dev wget memcached \
libreadline-dev libncurses-dev libmemcached-dev libbz2-dev \
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
libcloog-ppl0 libelf-dev libdwarf-dev libunwind7-dev subversion &
git clone git://github.com/libevent/libevent.git --quiet &
git clone git://github.com/bagder/curl.git --quiet &
svn checkout http://google-glog.googlecode.com/svn/trunk/ google-glog --quiet &
wget http://www.canonware.com/download/jemalloc/jemalloc-3.0.0.tar.bz2 --quiet &
# init submodules
git submodule update --init
# wait until all background processes finished
FAIL=0
for job in `jobs -p`
do
echo "waiting for background job $job"
wait $job || let "FAIL+=1"
done
if [ "$FAIL" == "0" ];
then
echo "all downloads finished"
else
echo "$FAIL errors while downloading!"
exit 100
fi
# 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
git clone git://github.com/libevent/libevent.git
cd libevent
git checkout release-1.4.14b-stable
cat ../hphp/third_party/libevent-1.4.14.fb-changes.diff | patch -p1
./autogen.sh
./configure --prefix=$CMAKE_PREFIX_PATH
make
make -j $CPUS
make install
cd ..
# curl
git clone git://github.com/bagder/curl.git
cd curl
./buildconf
./configure --prefix=$CMAKE_PREFIX_PATH
make
make -j $CPUS
make install
cd ..
# glog
svn checkout http://google-glog.googlecode.com/svn/trunk/ google-glog
cd google-glog
./configure --prefix=$CMAKE_PREFIX_PATH
make
make -j $CPUS
make install
cd ..
# jemaloc
wget http://www.canonware.com/download/jemalloc/jemalloc-3.0.0.tar.bz2
tar xjvf jemalloc-3.0.0.tar.bz2
cd jemalloc-3.0.0
./configure --prefix=$CMAKE_PREFIX_PATH
make
make -j $CPUS
make install
cd ..
@@ -68,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
+21 -65
Ver Arquivo
@@ -16,42 +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/vm util)
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()
# 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)
@@ -60,43 +30,29 @@ add_subdirectory(third_party/timelib)
add_subdirectory(third_party/lz4)
add_subdirectory(third_party/double-conversion)
add_subdirectory(third_party/folly)
add_subdirectory(third_party/libzip)
if(ENABLE_FASTCGI)
add_subdirectory(third_party/ti)
add_subdirectory(third_party/thrift)
endif()
foreach (CXX_FILE ${CXX_SOURCES})
if(${CXX_FILE} MATCHES ".no.cpp$")
SET_SOURCE_FILES_PROPERTIES(
${CXX_FILE}
PROPERTIES
COMPILE_FLAGS -O0
)
endif()
endforeach()
add_custom_command(
OUTPUT hphp_repo_schema.h hphp_build_info.cpp
COMMAND hphp/util/generate_buildinfo.sh
DEPENDS ${CXX_SOURCES} ${C_SOURCES}
WORKING_DIRECTORY ${HPHP_HOME}
COMMENT "Generating Repo Schema ID and Compiler ID"
VERBATIM)
ADD_LIBRARY(hphp_runtime_static STATIC
hphp_repo_schema.h hphp_build_info.cpp
${CXX_SOURCES} ${C_SOURCES} ${ASM_SOURCES})
SET_TARGET_PROPERTIES(hphp_runtime_static PROPERTIES OUTPUT_NAME "hphp_runtime")
SET_TARGET_PROPERTIES(hphp_runtime_static PROPERTIES PREFIX "lib")
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_subdirectory("tools/bootstrap")
add_subdirectory(vixl)
add_subdirectory(neo)
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 ()
# Keep this last
add_subdirectory(tools/hphpize)
+226
Ver Arquivo
@@ -0,0 +1,226 @@
"D<something>"
- Deleted legacy register allocator and removed the -vEval.HHIRXls option
"Coolio" 21-Jan-2014
- Turn on Region JIT
- FastCGI fixes, perf improvements
- ext_zend_compat fixes
- Turn on XLS Register Allocator by default
- Fix server stats reporting
- 'num' scalar typehint that accepts both ints and floats
- fix support for typedef'd namespaces
- don't swallow fatals when autoloading
- Map collections learned the in-place retain() and retainWithKey()
- rename Set::difference() to Set::removeAll()
- Update Set to retain element insertion order
- remove APC stats
- Fixes for ARM mode
- FrozenMap collection
- Deprecated Vector|Set|Map::put() method removed
- == between Frozen{Vector|Set|Map} and {Vector|Set|Map} now can return true
"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
- Direct invocation of callable arrays: $f = [$cls_or_obj, 'method']; $f()
- ASAN clean
- Support dynamically loadable extensions
- Support loading mini-systemlibs from extensions
"Tabasco" 30-Sep-2013
- Fix issues with __toString() functions that return non-string values
- Don't allow mock classes to extend collection classes
- Smarter memory allocation and scheduling for NUMA systems
- Improve profiler performance in the jit
- Fix several Zend compatibility issues
- Fix several bugs uncovered by ASAN
- Add collection support to array_keys, array_values, and array_combine
- Return a set-like array from Set::toArray
- Add to(Vector|Map|StableMap|Set) methods to collections
- Collections convert to boolean false when empty
- get_class_vars invokes the autoloader when necessary
- Rework the Zend compatibility layer to be more robust
- Allow traits to implement interfaces
- Support arbitrary expressions inside empty()
"Bobotie" 16-Sep-2013
- HNI (HipHop Native Interface) for calling C++ functions from PHP
- Fix PropertyAccessorMap::isset
- Expose more POSIX constants
- Fixed behavior of stream_get_contents when default args are used.
- Implement str_getcsv, and fix some fgetcsv related issues.
- [IPv6] Fix stream_socket_recvfrom & stream_socket_sendto.
- [IPv6] Fix socket_sentto_recvfrom_ipv6_udp Zend compatibility.
- Optimize closure invocation and __invoke (~3x faster to invoke)
- Import gettext extension
- string and object allocation optimizations (reduced memory usage for both)
- Import YAML extension
- Import ftp extension
"Kimchi" 2-Sep-2013
- Fix order of custom attributes and visibility in ctor arg promotion
- Implement CachingIterator
- Implement RecursiveCachingIterator
- Generalized heuristic for choosing when to inline in the jit
- Introduced a Zend compatibility layer to compile extensions
- Imported calendar extension
- Use gcc-4.8.1 by default
- Improve hhvm 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
- Fix ArrayIterator constructor PHP compatibility
- Enable building against libmemcached 1.0.8
- Debugger: $_ not cleared but still printed after exception
- Fix clone of SplPriorityQueue
- Debugger: Fix bugs when multiple threads hit the same breakpoint
- Fix several namespace bugs
- Several PHP compatibility fixes for ArrayObject and ArrayIterator
- Fix list assignment with collection literals
- support "tuple(...)" in initializer expressions
- HHVM should compile with libmemcached 1.0.9+
- Support "(new Vector {..})->method()" style syntax
- use trigger_error in PHP for Redis user errors
- multiple simplexml fixes
- fixed serialize/unserialize for SplObjectStorage
- Implement ReflectionParameter::IsCallable()
"Achiote" 19-Aug-2013
- Async stack traces in the debugger via the "wa" command
- Fix late static binding in static closures
- Fix breakpoints on generators
- Add SplObserver and SplSubject interfaces
- Update Iterable interface and add toArray() method
- Allow __get for undefined properties
- Implement get_included_files()
- Limit use of huge pages
"Churrasco" 05-Aug-2013
- Implement stream_is_local
- Implement read support for .phar
- Implement assert with string arguments
- Implement RecursiveArrayIterator
- Implement php_strip_whitespace()
- Support for timeouts in cli mode
- Closure allocation optimizations (~2x faster to allocate a closure)
- Implement Redis session handler
- New memory profiler, hhprof, with pprof compatible output
- Update isset($string[$k]) and empty($string[$k) to PHP 5.5 semantics
- Fixed a few parser bugs
- Fixed a few bugs with token_get_all()
- Fix (string)$obj semantics when __toString() is not defined
"Tamale" 22-Jul-2013
- Optimize vector-shaped Arrays (arrays with keys in range 0..size-1)
- Enable HHBC by default in debug builds
- Implement SplObjectStorage::getInfo()
- Initial rough draft of xhpast2, a replacement for xhpast
- fix compilation on Ubuntu 13.04
- OSX changes, next round
- Modify PHP's ext/standard/math/tests/(pow|abs).phpt to be HHVM friendly
- add XHP comment syntax based on http://www.w3.org/TR/REC-xml/#sec-comments
"Wasabi Peas" 08-Jul-2013
- always_assert when we run out of TC space
- Initial changes to get HHVM compiling on OSX
- Consolidate ObjectData and Instance
- Prototype heap tracing framework & Heap profiler
- Better JIT code generation for Mod and Div
- Fixes to enable compilation with clang
- Support for yield k => v
- Make HHVM's command line parsing closer to PHP
- Implement Redis extension
- Implement LimitIterator from SPL
- add SessionHandler from PHP 5.4
- Numerous Debugger fixes and new developer docs for Debugger
- Ported many extension tests to PHP
+1
Ver Arquivo
@@ -49,3 +49,4 @@ add_definitions(-DALWAYS_ASSERT=1)
ADD_LIBRARY(hphp_analysis STATIC ${CXX_SOURCES} ${C_SOURCES})
target_link_libraries(hphp_analysis ${Boost_LIBRARIES})
add_dependencies(hphp_analysis hphp_parser)
+35 -61
Ver Arquivo
@@ -28,14 +28,14 @@
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/object_method_expression.h"
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/include_expression.h"
#include "hphp/compiler/expression/closure_expression.h"
#include "hphp/compiler/expression/yield_expression.h"
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/statement/catch_statement.h"
@@ -64,14 +64,14 @@
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/util/parser/location.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/parser/location.h"
#include "hphp/util/util.h"
#define spc(T,p) boost::static_pointer_cast<T>(p)
#define dpc(T,p) boost::dynamic_pointer_cast<T>(p)
#define spc(T,p) static_pointer_cast<T>(p)
#define dpc(T,p) dynamic_pointer_cast<T>(p)
using namespace HPHP;
using std::string;
@@ -746,15 +746,6 @@ void AliasManager::killLocals() {
goto kill_it;
case Expression::KindOfBinaryOpExpression:
if (!(effects & emask) &&
getOpForAssignmentOp(spc(BinaryOpExpression, e)->getOp())) {
if (okToKill(spc(BinaryOpExpression, e)->getExp1(), false)) {
e->setContext(Expression::DeadStore);
m_replaced++;
++it;
continue;
}
}
cleanInterf(spc(BinaryOpExpression, e)->getExp1(), ++it, end, depth);
continue;
@@ -1526,8 +1517,7 @@ ExpressionPtr AliasManager::canonicalizeNode(
e->is(Expression::KindOfSimpleVariable) &&
!e->isThis()) {
Symbol *s = spc(SimpleVariable, e)->getSymbol();
if (s && !s->isParameter() && !s->isGeneratorParameter() &&
!s->isClosureVar()) {
if (s && !s->isParameter() && !s->isClosureVar()) {
rep = e->makeConstant(m_arp, "null");
Compiler::Error(Compiler::UseUndeclaredVariable, e);
if (m_variables->getAttribute(VariableTable::ContainsCompact)) {
@@ -1587,6 +1577,7 @@ ExpressionPtr AliasManager::canonicalizeNode(
cur = next;
}
if (!m_inCall &&
!last->is(Expression::KindOfAwaitExpression) &&
!last->is(Expression::KindOfYieldExpression) &&
ae->isUnused() && m_accessList.isLast(ae) &&
!e->hasAnyContext(Expression::AccessContext |
@@ -1934,6 +1925,7 @@ StatementPtr AliasManager::canonicalizeRecur(StatementPtr s, int &ret) {
switch (stype) {
case Statement::KindOfUseTraitStatement:
case Statement::KindOfTraitRequireStatement:
case Statement::KindOfTraitPrecStatement:
case Statement::KindOfTraitAliasStatement:
return StatementPtr();
@@ -1975,7 +1967,7 @@ StatementPtr AliasManager::canonicalizeRecur(StatementPtr s, int &ret) {
}
case Statement::KindOfIfBranchStatement:
always_assert(0);
always_assert(false);
break;
case Statement::KindOfForStatement: {
@@ -2367,9 +2359,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:
@@ -2540,8 +2529,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;
@@ -2614,7 +2605,7 @@ private:
ExpressionListPtr el(
new ExpressionList(
CONSTRUCT_PARAMS(target),
CONSTRUCT_EXP(target),
ExpressionList::ListKindComma));
if (target->isUnused()) {
el->setUnused(true);
@@ -2640,8 +2631,11 @@ private:
if (sv && se) {
const string &s = se->getLiteralString();
if (s.empty()) return ExpressionPtr();
if (interface_supports_array(s)) {
// This could be an array, so don't assert anything
if (interface_supports_array(s) ||
interface_supports_string(s) ||
interface_supports_int(s) ||
interface_supports_double(s)) {
// This could be a primitive type, so don't assert anything
return ExpressionPtr();
}
TypePtr o(Type::CreateObjectType(Util::toLower(s)));
@@ -2955,7 +2949,7 @@ private:
slistPtr->insertElement(
ExpStatementPtr(
new ExpStatement(
CONSTRUCT_PARAMS(slistPtr), assertion)),
CONSTRUCT_STMT(slistPtr), assertion)),
idx);
}
break;
@@ -3036,12 +3030,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 +3302,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());
}
@@ -3327,19 +3327,12 @@ public:
DataFlowWalker::walk(*this);
ControlBlock *b = m_graph.getDfBlock(1);
std::map<std::string,int>::iterator it = m_gidMap.find("v:this");
if (m->getOrigGeneratorFunc()) {
BitOps::set(m_gidMap.size(), b->getRow(DataFlow::PRefIn),
BitOps::Bits(-1));
BitOps::set(m_gidMap.size(), b->getRow(DataFlow::PInitIn),
BitOps::Bits(-1));
} else {
if (it != m_gidMap.end() && it->second) {
b->setBit(DataFlow::PRefIn, it->second);
b->setBit(DataFlow::PInitIn, it->second);
}
updateParamInfo(m->getParams(), Option::HardTypeHints);
updateParamInfo(m->getFunctionScope()->getClosureVars(), false);
if (it != m_gidMap.end() && it->second) {
b->setBit(DataFlow::PRefIn, it->second);
b->setBit(DataFlow::PInitIn, it->second);
}
updateParamInfo(m->getParams(), Option::HardTypeHints);
updateParamInfo(m->getFunctionScope()->getClosureVars(), false);
}
void updateParamInfo(ExpressionListPtr el, bool useDefaults) {
@@ -3579,25 +3572,6 @@ public:
}
}
if (auto rs = dynamic_pointer_cast<ReturnStatement>(cp)) {
std::vector<std::string> lnames;
VariableTableConstPtr vars = cp->getFunctionScope()->getVariables();
vars->getLocalVariableNames(lnames);
for (auto& l : lnames) {
int id = m_gidMap["v:" + l];
if (id && !m_block->getBit(DataFlow::PInitOut, id)) {
rs->addNonRefcounted(l);
} else {
auto sym = vars->getSymbol(l);
auto dt = vars->getFinalType(l)->getDataType();
if (!sym->isStatic()
&& !IS_REFCOUNTED_TYPE(dt) && dt != KindOfUnknown) {
rs->addNonRefcounted(l);
}
}
}
}
return DataFlowWalker::after(cp);
}
private:
@@ -3613,7 +3587,7 @@ public:
bool walk() { ControlFlowGraphWalker::walk(*this); return m_changed; }
int afterEach(ConstructRawPtr p, int i, ConstructPtr kid) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(kid)) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(kid)) {
if (e->isTypeAssertion()) return WalkContinue; // nothing to do
bool safeForProp =
+98 -87
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"
@@ -46,14 +47,14 @@
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/runtime/ext/ext_json.h"
#include "hphp/runtime/base/zend/zend_printf.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/util/atomic.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/util/process.h"
#include "hphp/util/job_queue.h"
#include "hphp/util/job-queue.h"
#include "hphp/util/timer.h"
using namespace HPHP;
@@ -456,8 +457,10 @@ void AnalysisResult::markRedeclaringClasses() {
* as redeclaring for now.
*/
for (auto& kv : m_classAliases) {
markRedeclaring(Util::toLower(kv.first));
markRedeclaring(Util::toLower(kv.second));
assert(kv.first == Util::toLower(kv.first));
assert(kv.second == Util::toLower(kv.second));
markRedeclaring(kv.first);
markRedeclaring(kv.second);
}
/*
@@ -467,7 +470,8 @@ void AnalysisResult::markRedeclaringClasses() {
* that things like 'instanceof Foo' will not mean the same thing.
*/
for (auto& name : m_typeAliasNames) {
markRedeclaring(Util::toLower(name));
assert(Util::toLower(name) == name);
markRedeclaring(name);
}
}
@@ -485,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 =
@@ -504,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);
@@ -567,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() {
@@ -584,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);
}
}
}
}
@@ -602,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;
}
@@ -625,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++);
@@ -644,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(),
@@ -964,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() {}
@@ -980,15 +994,15 @@ public:
virtual void doJob(BlockScope *scope) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumDoJobCalls);
++AnalysisResult::s_NumDoJobCalls;
ConcurrentBlockScopeRawPtrIntHashMap::accessor acc;
AnalysisResult::s_DoJobUniqueScopes.insert(acc,
BlockScopeRawPtr(scope));
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);
@@ -1040,13 +1054,13 @@ public:
break;
case BlockScope::MarkProcessing:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumForceRerunGlobal);
++AnalysisResult::s_NumForceRerunGlobal;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
pf->first->setForceRerun(true);
break;
case BlockScope::MarkProcessed:
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateGlobal);
++AnalysisResult::s_NumReactivateGlobal;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
if (visitor->activateScope(pf->first)) {
visitor->enqueue(pf->first);
@@ -1082,7 +1096,7 @@ public:
int m = pf->first->getMark();
if (pf->second & useKinds && m == BlockScope::MarkProcessed) {
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumReactivateUseKinds);
++AnalysisResult::s_NumReactivateUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
bool ready = visitor->activateScope(pf->first);
always_assert(!ready);
@@ -1106,7 +1120,7 @@ public:
// in its entirety. Thus, we must force it to run again in
// order to be able to observe all the updates.
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
atomic_inc(AnalysisResult::s_NumForceRerunUseKinds);
++AnalysisResult::s_NumForceRerunUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
always_assert(pf->first->getNumDepsToWaitFor() == 0);
pf->first->setForceRerun(true);
@@ -1177,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)
@@ -1222,7 +1236,7 @@ template <typename When>
void
AnalysisResult::preWaitCallback(bool first,
const BlockScopeRawPtrQueue &scopes,
void *opaque) {
void *context) {
// default is no-op
}
@@ -1231,17 +1245,17 @@ bool
AnalysisResult::postWaitCallback(bool first,
bool again,
const BlockScopeRawPtrQueue &scopes,
void *opaque) {
void *context) {
// default is no-op
return again;
}
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
int AnalysisResult::s_NumDoJobCalls = 0;
int AnalysisResult::s_NumForceRerunGlobal = 0;
int AnalysisResult::s_NumReactivateGlobal = 0;
int AnalysisResult::s_NumForceRerunUseKinds = 0;
int AnalysisResult::s_NumReactivateUseKinds = 0;
std::atomic<int> AnalysisResult::s_NumDoJobCalls(0);
std::atomic<int> AnalysisResult::s_NumForceRerunGlobal(0);
std::atomic<int> AnalysisResult::s_NumReactivateGlobal(0);
std::atomic<int> AnalysisResult::s_NumForceRerunUseKinds(0);
std::atomic<int> AnalysisResult::s_NumReactivateUseKinds(0);
ConcurrentBlockScopeRawPtrIntHashMap
AnalysisResult::s_DoJobUniqueScopes;
@@ -1296,7 +1310,7 @@ struct BIPairCmp {
template <typename When>
void
AnalysisResult::processScopesParallel(const char *id,
void *opaque /* = NULL */) {
void *context /* = NULL */) {
BlockScopeRawPtrQueue scopes;
getScopesSet(scopes);
@@ -1333,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
{
@@ -1387,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();
@@ -1516,7 +1530,7 @@ DepthFirstVisitor<InferTypes, OptVisitor>::visitScope(BlockScopeRawPtr scope) {
// there are potentially AST nodes which are interested in the updated
// return type
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumForceRerunSelfCaller);
++RescheduleException::s_NumForceRerunSelfCaller;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
scope->setForceRerun(true);
}
@@ -1533,7 +1547,7 @@ DepthFirstVisitor<InferTypes, OptVisitor>::visitScope(BlockScopeRawPtr scope) {
// potential deadlock detected- reschedule
// this scope to run at a later time
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumReschedules);
++RescheduleException::s_NumReschedules;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
ret |= scope->getUpdated();
if (m) {
@@ -1559,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: " <<
@@ -1590,9 +1605,9 @@ bool AnalysisResult::postWaitCallback<InferTypes>(
}
#ifdef HPHP_INSTRUMENT_TYPE_INF
int RescheduleException::s_NumReschedules = 0;
int RescheduleException::s_NumForceRerunSelfCaller = 0;
int RescheduleException::s_NumRetTypesChanged = 0;
std::atomic<int> RescheduleException::s_NumReschedules(0);
std::atomic<int> RescheduleException::s_NumForceRerunSelfCaller(0);
std::atomic<int> RescheduleException::s_NumRetTypesChanged(0);
LProfileMap BaseTryLock::s_LockProfileMap;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
@@ -1601,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
@@ -1617,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);
}
}
@@ -1665,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());
}
@@ -1679,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;
@@ -1707,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);
+25 -15
Ver Arquivo
@@ -24,19 +24,20 @@
#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"
#include "hphp/util/string-bag.h"
#include "hphp/util/thread-local.h"
#include <boost/graph/adjacency_list.hpp>
#include "tbb/concurrent_hash_map.h"
#include <tbb/concurrent_hash_map.h>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
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();
@@ -238,6 +240,14 @@ public:
ClassScopePtr findClass(const std::string &className,
FindClassBy by);
/*
* Returns: whether the given name is the name of any type aliases
* in the whole program.
*/
bool isTypeAliasName(const std::string& name) const {
return m_typeAliasNames.count(name);
}
/**
* Find all the redeclared classes by the name, excluding system classes.
* Note that system classes cannot be redeclared.
@@ -335,12 +345,12 @@ private:
std::string m_outputPath;
public:
AnalysisResultPtr shared_from_this() {
return boost::static_pointer_cast<AnalysisResult>
return static_pointer_cast<AnalysisResult>
(BlockScope::shared_from_this());
}
AnalysisResultConstPtr shared_from_this() const {
return boost::static_pointer_cast<const AnalysisResult>
return static_pointer_cast<const AnalysisResult>
(BlockScope::shared_from_this());
}
@@ -396,12 +406,12 @@ public:
s_changedScopesMapThreadLocal);
#ifdef HPHP_INSTRUMENT_PROCESS_PARALLEL
static int s_NumDoJobCalls;
static std::atomic<int> s_NumDoJobCalls;
static ConcurrentBlockScopeRawPtrIntHashMap s_DoJobUniqueScopes;
static int s_NumForceRerunGlobal;
static int s_NumReactivateGlobal;
static int s_NumForceRerunUseKinds;
static int s_NumReactivateUseKinds;
static std::atomic<int> s_NumForceRerunGlobal;
static std::atomic<int> s_NumReactivateGlobal;
static std::atomic<int> s_NumForceRerunUseKinds;
static std::atomic<int> s_NumReactivateUseKinds;
#endif /* HPHP_INSTRUMENT_PROCESS_PARALLEL */
private:
@@ -429,9 +439,9 @@ public:
Exception(), m_scope(scope) {}
BlockScopeRawPtr &getScope() { return m_scope; }
#ifdef HPHP_INSTRUMENT_TYPE_INF
static int s_NumReschedules;
static int s_NumForceRerunSelfCaller;
static int s_NumRetTypesChanged;
static std::atomic<int> s_NumReschedules;
static std::atomic<int> s_NumForceRerunSelfCaller;
static std::atomic<int> s_NumRetTypesChanged;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
private:
BlockScopeRawPtr m_scope;
+3 -3
Ver Arquivo
@@ -23,17 +23,17 @@ using namespace HPHP;
bool FunctionWalker::SkipRecurse(ConstructPtr cp) {
StatementPtr s(
boost::dynamic_pointer_cast<Statement>(cp));
dynamic_pointer_cast<Statement>(cp));
return SkipRecurse(s);
}
bool FunctionWalker::SkipRecurse(ConstructConstPtr cp) {
StatementConstPtr s(
boost::dynamic_pointer_cast<const Statement>(cp));
dynamic_pointer_cast<const Statement>(cp));
return SkipRecurse(s);
}
bool FunctionWalker::SkipRecurse(ConstructRawPtr cp) {
StatementRawPtr s(
boost::dynamic_pointer_cast<Statement>(cp));
dynamic_pointer_cast<Statement>(cp));
return SkipRecurse(s);
}
+4 -5
Ver Arquivo
@@ -14,10 +14,11 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/analysis/block_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/constant_table.h"
@@ -94,7 +95,7 @@ FunctionScopeRawPtr BlockScope::getContainingNonClosureFunction() {
// walk out through all the closures
while (bs && bs->is(BlockScope::FunctionScope)) {
HPHP::FunctionScope *fs = static_cast<HPHP::FunctionScope*>(bs);
if (!fs->isClosure() && !fs->isGeneratorFromClosure()) {
if (!fs->isClosure()) {
return FunctionScopeRawPtr(fs);
}
bs = bs->m_outerScope.get();
@@ -154,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;
+2 -2
Ver Arquivo
@@ -23,7 +23,7 @@
#include "hphp/util/lock.h"
#include "hphp/runtime/base/macros.h"
#include "tbb/concurrent_hash_map.h"
#include <tbb/concurrent_hash_map.h>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -66,7 +66,7 @@ typedef SimpleMutex InferTypesMutex;
* Base class of ClassScope and FunctionScope.
*/
class BlockScope : private boost::noncopyable,
public boost::enable_shared_from_this<BlockScope> {
public std::enable_shared_from_this<BlockScope> {
public:
enum KindOf {
ClassScope,
+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_
+138 -133
Ver Arquivo
@@ -34,14 +34,15 @@
#include "hphp/compiler/statement/function_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/compiler/statement/class_variable.h"
#include "hphp/compiler/statement/class_constant.h"
#include "hphp/compiler/statement/use_trait_statement.h"
#include "hphp/compiler/statement/trait_require_statement.h"
#include "hphp/compiler/statement/trait_prec_statement.h"
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/util/util.h"
#include <boost/foreach.hpp>
@@ -62,7 +63,7 @@ ClassScope::ClassScope(KindOf kindOf, const std::string &name,
m_kindOf(kindOf), m_derivesFromRedeclaring(FromNormal),
m_traitStatus(NOT_FLATTENED), m_volatile(false),
m_persistent(false), m_derivedByDynamic(false),
m_sep(false), m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) {
m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) {
m_dynamic = Option::IsDynamicClass(m_name);
@@ -92,7 +93,7 @@ ClassScope::ClassScope(AnalysisResultPtr ar,
m_kindOf(KindOfObjectClass), m_derivesFromRedeclaring(FromNormal),
m_traitStatus(NOT_FLATTENED), m_dynamic(false),
m_volatile(false), m_persistent(false),
m_derivedByDynamic(false), m_sep(false), m_needsCppCtor(false),
m_derivedByDynamic(false), m_needsCppCtor(false),
m_needsInit(true), m_knownBases(0) {
BOOST_FOREACH(FunctionScopePtr f, methods) {
if (f->getName() == "__construct") setAttribute(HasConstructor);
@@ -403,23 +404,12 @@ MethodStatementPtr
ClassScope::importTraitMethod(const TraitMethod& traitMethod,
AnalysisResultPtr ar,
string methName,
GeneratorRenameMap& genRenameMap,
const std::map<string, MethodStatementPtr>&
importedTraitMethods) {
MethodStatementPtr meth = traitMethod.m_method;
string origMethName = traitMethod.m_originalName;
ModifierExpressionPtr modifiers = traitMethod.m_modifiers;
if (meth->getOrigGeneratorFunc()) {
const string &name = meth->getOrigGeneratorFunc()->getName();
if (!importedTraitMethods.count(name)) {
// Dont import the generator, if the origGenerator wasnt imported
// this happens when a generator in the trait is hidden by a non-generator
// method in the importing class.
return MethodStatementPtr();
}
}
MethodStatementPtr cloneMeth = dynamic_pointer_cast<MethodStatement>(
dynamic_pointer_cast<ClassStatement>(m_stmt)->addClone(meth));
cloneMeth->setName(methName);
@@ -434,17 +424,9 @@ ClassScope::importTraitMethod(const TraitMethod& traitMethod,
ClassScopePtr cScope = dynamic_pointer_cast<ClassScope>(shared_from_this());
cloneMeth->fixupSelfAndParentTypehints( cScope );
// Generator methods need to be renamed, otherwise code gen produces multiple
// continuation classes with the same name
if (funcScope->isGenerator()) {
const string& newName = getNewGeneratorName(funcScope, genRenameMap);
methName = origMethName = newName;
cloneMeth->setName(newName);
cloneMeth->setOriginalName(newName);
}
FunctionScopePtr cloneFuncScope
(new HPHP::FunctionScope(funcScope, ar, methName, origMethName, cloneMeth,
cloneMeth->getModifiers()));
cloneMeth->getModifiers(), cScope->isUserClass()));
cloneMeth->resetScope(cloneFuncScope, true);
cloneFuncScope->setOuterScope(shared_from_this());
informClosuresAboutScopeClone(cloneMeth, cloneFuncScope, ar);
@@ -492,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,
@@ -552,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();
@@ -568,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;
@@ -599,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()
);
}
}
@@ -615,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++) {
@@ -632,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();
@@ -642,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());
@@ -654,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
@@ -666,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) {
@@ -682,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();
@@ -714,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++) {
@@ -750,89 +800,18 @@ void ClassScope::removeSpareTraitAbstractMethods(AnalysisResultPtr ar) {
}
}
const string& ClassScope::getNewGeneratorName(
FunctionScopePtr genFuncScope, GeneratorRenameMap &genRenameMap) {
assert(genFuncScope->isGenerator());
const string& oldName = genFuncScope->getName();
GeneratorRenameMap::iterator mapIt = genRenameMap.find(oldName);
if (mapIt != genRenameMap.end()) {
return mapIt->second;
}
string newName = ParserBase::newContinuationName(
oldName + "_" + lexical_cast<string>(genFuncScope->getNewID())
);
genRenameMap[oldName] = newName;
return genRenameMap[oldName];
}
void
ClassScope::renameCreateContinuationCalls(AnalysisResultPtr ar,
ConstructPtr c,
ImportedMethodMap &importedMethods) {
if (!c) return;
SimpleFunctionCallPtr funcCall = dynamic_pointer_cast<SimpleFunctionCall>(c);
if (funcCall && funcCall->getName() == "hphp_create_continuation") {
ExpressionListPtr params = funcCall->getParams();
assert(params->getCount() >= 2);
const string &oldClassName =
dynamic_pointer_cast<ScalarExpression>((*params)[0])->getString();
ClassScopePtr oldClassScope = ar->findClass(oldClassName);
if (!oldClassScope || !oldClassScope->isTrait()) return;
const string &oldGenName =
dynamic_pointer_cast<ScalarExpression>((*params)[1])->getString();
MethodStatementPtr origGenStmt = importedMethods[Util::toLower(oldGenName)];
assert(origGenStmt);
const string &newGenName = origGenStmt->getOriginalName();
ExpressionPtr newGenExpr = funcCall->makeScalarExpression(ar, newGenName);
ExpressionPtr newClsExpr = funcCall->makeScalarExpression(ar, getName());
(*params)[0] = newClsExpr;
(*params)[1] = newGenExpr;
funcCall->analyzeProgram(ar);
return;
}
for (int i=0; i < c->getKidCount(); i++) {
renameCreateContinuationCalls(ar, c->getNthKid(i), importedMethods);
}
}
void ClassScope::relinkGeneratorMethods(
AnalysisResultPtr ar,
ImportedMethodMap &importedMethods) {
for (ImportedMethodMap::const_iterator methIt =
importedMethods.begin(); methIt != importedMethods.end(); methIt++) {
MethodStatementPtr newMeth = methIt->second;
// Skip non-generator methods
if (!newMeth) continue;
if (newMeth->getOrigGeneratorFunc()) {
// Get corresponding original generator method in the current class
const string& origGenName = newMeth->getOrigGeneratorFunc()->getName();
MethodStatementPtr origGenStmt = importedMethods[origGenName];
assert(origGenStmt);
// It must be an orig gen func already, we're just updating to point
// to the corresponding method cloned from the trait
assert(origGenStmt->getGeneratorFunc());
newMeth->setOrigGeneratorFunc(origGenStmt);
origGenStmt->setGeneratorFunc(newMeth);
}
// OrigGenerator methods need to have their hphp_create_continuation calls
// patched to the new generator name.
if (newMeth->getGeneratorFunc()) {
renameCreateContinuationCalls(ar, newMeth, importedMethods);
}
}
}
void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
// 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) {
@@ -849,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
@@ -880,9 +894,7 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
}
std::map<string, MethodStatementPtr> importedTraitMethods;
std::vector<std::pair<string,const TraitMethod*> > importedTraitsWithOrigName;
GeneratorRenameMap genRenameMap;
std::vector<std::pair<string,const TraitMethod*>> importedTraitsWithOrigName;
// Actually import the methods
for (MethodToTraitListMap::const_iterator
@@ -896,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 :
@@ -907,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;
@@ -928,15 +937,12 @@ void ClassScope::importUsedTraits(AnalysisResultPtr ar) {
const TraitMethod *traitMethod = importedTraitsWithOrigName[i].second;
MethodStatementPtr newMeth = importTraitMethod(
*traitMethod, ar, Util::toLower(traitMethod->m_originalName),
genRenameMap, importedTraitMethods);
importedTraitMethods);
if (newMeth) {
importedTraitMethods[sourceName] = newMeth;
}
}
// Relink generator and origGenerator methods
relinkGeneratorMethods(ar, importedTraitMethods);
// Import trait properties
importTraitProperties(ar);
@@ -1198,10 +1204,10 @@ void ClassScope::getAllParents(AnalysisResultConstPtr ar,
std::vector<std::string> &names) {
if (m_stmt) {
if (isInterface()) {
boost::dynamic_pointer_cast<InterfaceStatement>
dynamic_pointer_cast<InterfaceStatement>
(m_stmt)->getAllParents(ar, names);
} else {
boost::dynamic_pointer_cast<ClassStatement>
dynamic_pointer_cast<ClassStatement>
(m_stmt)->getAllParents(ar, names);
}
} else {
@@ -1237,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 -19
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 {
@@ -169,14 +170,11 @@ public:
return m_derivedByDynamic;
}
/* Whether this class is brought in by a separable extension */
void setSepExtension() { m_sep = true;}
bool isSepExtension() const { return m_sep;}
/**
* Get/set attributes.
*/
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 {
@@ -305,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);
/**
@@ -373,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;
@@ -382,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;
@@ -407,7 +429,6 @@ private:
typedef std::list<TraitMethod> TraitMethodList;
typedef std::map<std::string, TraitMethodList> MethodToTraitListMap;
typedef std::map<std::string, std::string> GeneratorRenameMap;
MethodToTraitListMap m_importMethToTraitMap;
typedef std::map<std::string, MethodStatementPtr> ImportedMethodMap;
@@ -424,7 +445,6 @@ private:
unsigned m_volatile:1; // for class_exists
unsigned m_persistent:1;
unsigned m_derivedByDynamic:1;
unsigned m_sep:1;
unsigned m_needsCppCtor:1;
unsigned m_needsInit:1;
// m_knownBases has a bit for each base class saying whether
@@ -433,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,
@@ -446,17 +469,15 @@ private:
MethodStatementPtr importTraitMethod(const TraitMethod& traitMethod,
AnalysisResultPtr ar,
std::string methName,
GeneratorRenameMap& genRenameMap,
const ImportedMethodMap &
importedTraitMethods);
void importTraitProperties(AnalysisResultPtr ar);
void relinkGeneratorMethods(AnalysisResultPtr ar,
ImportedMethodMap& importedMethods);
void findTraitMethodsToImport(AnalysisResultPtr ar, ClassScopePtr trait);
void importTraitRequirements(AnalysisResultPtr ar, ClassScopePtr trait);
MethodStatementPtr findTraitMethod(AnalysisResultPtr ar,
ClassScopePtr trait,
const std::string &methodName,
@@ -477,12 +498,6 @@ private:
bool hasMethod(const std::string &methodName) const;
const std::string& getNewGeneratorName(FunctionScopePtr genFuncScope,
GeneratorRenameMap& genRenameMap);
void renameCreateContinuationCalls(AnalysisResultPtr ar, ConstructPtr c,
ImportedMethodMap &importedMethods);
};
///////////////////////////////////////////////////////////////////////////////
+1 -1
Ver Arquivo
@@ -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 -1
Ver Arquivo
@@ -25,7 +25,7 @@
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
+5 -5
Ver Arquivo
@@ -64,8 +64,8 @@ typedef hphp_hash_map<ConstructRawPtr, ControlBlock*,
class ControlFlowBuilder : public FunctionWalker {
public:
ControlFlowBuilder(ControlFlowGraph *g, bool isGenerator) :
m_graph(g), m_pass(0), m_isGenerator(isGenerator), m_cur(0), m_head(0) {}
explicit ControlFlowBuilder(ControlFlowGraph *g) :
m_graph(g), m_pass(0), m_cur(0), m_head(0) {}
int before(ConstructRawPtr cp);
int after(ConstructRawPtr cp);
@@ -161,7 +161,6 @@ private:
ControlFlowGraph *m_graph;
AstWalkerStateVec m_state;
int m_pass;
bool m_isGenerator;
ControlBlock *m_cur;
ControlBlock *m_head;
@@ -246,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();
@@ -417,7 +417,7 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
case Statement::KindOfReturnStatement: {
setEdge(s, AfterConstruct, root(), AfterConstruct);
if (!m_isGenerator) noFallThrough(s);
noFallThrough(s);
/*
* Since almost anything in php /might/ throw, we
* approximate, and add edges from the beginning and
@@ -868,7 +868,7 @@ ControlFlowGraph *ControlFlowGraph::buildControlFlow(MethodStatementPtr m) {
ControlFlowGraph *graph = new ControlFlowGraph;
graph->m_stmt = m;
ControlFlowBuilder cfb(graph, !!m->getOrigGeneratorFunc());
ControlFlowBuilder cfb(graph);
cfb.run(m->getStmts());
graph->m_nextDfn = 1;
depth_first_visit(*graph, cfb.head(),
+2 -1
Ver Arquivo
@@ -37,10 +37,11 @@ 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)
CODE_ERROR_ENTRY(InvalidInstantiation)
CODE_ERROR_ENTRY(InvalidYield)
CODE_ERROR_ENTRY(InvalidAwait)
CODE_ERROR_ENTRY(BadDefaultValueType)
CODE_ERROR_ENTRY(InvalidMethodDefinition)
+8 -8
Ver Arquivo
@@ -221,16 +221,16 @@ void DataFlow::ComputePartialDying(const ControlFlowGraph &g) {
// DataFlowWalker
int DataFlowWalker::after(ConstructRawPtr cp) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(cp)) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(cp)) {
switch (e->getKindOf()) {
case Expression::KindOfSimpleVariable:
if (!boost::static_pointer_cast<SimpleVariable>(
if (!static_pointer_cast<SimpleVariable>(
e)->getAlwaysStash()) {
return WalkContinue;
}
break;
case Expression::KindOfBinaryOpExpression:
if (boost::static_pointer_cast<BinaryOpExpression>(
if (static_pointer_cast<BinaryOpExpression>(
e)->isShortCircuitOperator()) {
break;
}
@@ -246,7 +246,7 @@ int DataFlowWalker::after(ConstructRawPtr cp) {
for (int i = 0, nk = e->getKidCount(); i < nk; i++) {
ExpressionPtr k = e->getNthExpr(i);
if (k && k->is(Expression::KindOfSimpleVariable) &&
!boost::static_pointer_cast<SimpleVariable>(
!static_pointer_cast<SimpleVariable>(
k)->getAlwaysStash()) {
process(k);
}
@@ -260,13 +260,13 @@ int DataFlowWalker::after(ConstructRawPtr cp) {
}
int DataFlowWalker::afterEach(ConstructRawPtr cur, int i, ConstructRawPtr kid) {
if (ExpressionRawPtr k = boost::dynamic_pointer_cast<Expression>(kid)) {
if (ExpressionRawPtr k = dynamic_pointer_cast<Expression>(kid)) {
if (k->is(Expression::KindOfSimpleVariable) &&
!boost::static_pointer_cast<SimpleVariable>(k)->getAlwaysStash()) {
if (ExpressionRawPtr e = boost::dynamic_pointer_cast<Expression>(cur)) {
!static_pointer_cast<SimpleVariable>(k)->getAlwaysStash()) {
if (ExpressionRawPtr e = dynamic_pointer_cast<Expression>(cur)) {
switch (e->getKindOf()) {
case Expression::KindOfBinaryOpExpression:
if (!boost::static_pointer_cast<BinaryOpExpression>(
if (!static_pointer_cast<BinaryOpExpression>(
e)->isShortCircuitOperator()) {
return WalkContinue;
}
+3 -3
Ver Arquivo
@@ -64,12 +64,12 @@ public:
}
StatementPtr visitStmtRecur(StatementPtr stmt) {
BlockScopeRawPtr scope = boost::dynamic_pointer_cast<LoopStatement>(stmt) ?
BlockScopeRawPtr scope = dynamic_pointer_cast<LoopStatement>(stmt) ?
stmt->getScope() : BlockScopeRawPtr();
for (int i = 0, n = stmt->getKidCount(); i < n; i++) {
if (ConstructPtr kid = stmt->getNthKid(i)) {
if (StatementPtr s = boost::dynamic_pointer_cast<Statement>(kid)) {
if (StatementPtr s = dynamic_pointer_cast<Statement>(kid)) {
if (FunctionWalker::SkipRecurse(s)) continue;
if (scope) scope->incLoopNestedLevel();
if (StatementPtr rep = visitStmtRecur(s)) {
@@ -78,7 +78,7 @@ public:
}
if (scope) scope->decLoopNestedLevel();
} else {
ExpressionPtr e = boost::dynamic_pointer_cast<Expression>(kid);
ExpressionPtr e = dynamic_pointer_cast<Expression>(kid);
if (ExpressionPtr rep = visitExprRecur(e)) {
stmt->setNthKid(i, rep);
stmt->getScope()->addUpdates(BlockScope::UseKindCaller);
+2 -2
Ver Arquivo
@@ -39,11 +39,11 @@ void Dictionary::build(MethodStatementPtr m) {
void Dictionary::build(StatementPtr stmt) {
for (int i = 0, n = stmt->getKidCount(); i < n; i++) {
if (ConstructPtr kid = stmt->getNthKid(i)) {
if (StatementPtr s = boost::dynamic_pointer_cast<Statement>(kid)) {
if (StatementPtr s = dynamic_pointer_cast<Statement>(kid)) {
if (FunctionWalker::SkipRecurse(s)) continue;
build(s);
} else {
ExpressionPtr e = boost::dynamic_pointer_cast<Expression>(kid);
ExpressionPtr e = dynamic_pointer_cast<Expression>(kid);
build(e);
}
}
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+303 -68
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,19 +111,20 @@ 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>&
#define IVA int32_t
#define HA int32_t
#define LA int32_t
#define IA int32_t
#define I64A int64_t
#define DA double
#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
@@ -131,7 +137,7 @@ public:
#undef SLA
#undef ILA
#undef IVA
#undef HA
#undef LA
#undef IA
#undef I64A
#undef DA
@@ -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;
@@ -531,7 +649,8 @@ private:
std::deque<PostponedNonScalars> m_postponedCinits;
std::deque<PostponedClosureCtor> m_postponedClosureCtors;
PendingIterVec m_pendingIters;
hphp_hash_set<std::string> m_generatorEmitted;
hphp_hash_map<std::string,FuncEmitter*> m_generatorEmitted;
hphp_hash_set<std::string> m_nonTopGeneratorEmitted;
hphp_hash_set<std::string> m_topMethodEmitted;
SymbolicStack m_evalStack;
bool m_evalStackIsUnknown;
@@ -541,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<HphpArray*> m_staticArrays;
std::vector<Array> m_staticArrays;
std::set<std::string,stdltistr> m_hoistables;
LocationPtr m_tempLoc;
std::map<StringData*, Label, string_data_lt> m_gotoLabels;
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 {
@@ -569,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);
@@ -599,6 +722,7 @@ public:
void emitResolveClsBase(Emitter& e, int pos);
void emitClsIfSPropBase(Emitter& e);
Id emitVisitAndSetUnnamedL(Emitter& e, ExpressionPtr exp);
Id emitSetUnnamedL(Emitter& e);
void emitPushAndFreeUnnamedL(Emitter& e, Id tempLocal, Offset start);
void emitContinuationSwitch(Emitter& e, int ncase);
DataType analyzeSwitch(SwitchStatementPtr s, SwitchState& state);
@@ -608,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);
@@ -628,6 +751,32 @@ public:
void postponeSinit(InterfaceStatementPtr m, FuncEmitter* fe, NonScalarVec* v);
void postponeCinit(InterfaceStatementPtr m, FuncEmitter* fe, NonScalarVec* v);
void emitPostponedMeths();
void bindUserAttributes(MethodStatementPtr meth,
FuncEmitter *fe,
bool &allowOverride);
void bindNativeFunc(MethodStatementPtr meth, FuncEmitter *fe);
void emitMethodMetadata(MethodStatementPtr meth,
ClosureUseVarVec* useVars,
bool top);
void fillFuncEmitterParams(FuncEmitter* fe,
ExpressionListPtr params,
bool builtin = false);
void emitMethodPrologue(Emitter& e, MethodStatementPtr meth);
void emitMethod(MethodStatementPtr meth);
std::pair<FuncEmitter*,bool> createFuncEmitterForGeneratorBody(
MethodStatementPtr meth,
FuncEmitter* fe,
vector<FuncEmitter*>& top_fes);
void emitAsyncMethod(MethodStatementPtr meth);
void emitGeneratorCreate(MethodStatementPtr meth);
void emitGeneratorBody(MethodStatementPtr meth);
void emitConstMethodCallNoParams(Emitter& e, string name);
void emitCreateStaticWaitHandle(Emitter& e, std::string cls,
std::function<void()> emitParam);
void emitSetFuncGetArgs(Emitter& e);
void emitMethodDVInitializers(Emitter& e,
MethodStatementPtr& meth,
Label& topOfBody);
void emitPostponedCtors();
void emitPostponedPSinit(PostponedNonScalars& p, bool pinit);
void emitPostponedPinits();
@@ -648,30 +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);
PreClass::Hoistable emitClass(Emitter& e, ClassScopePtr cNode,
bool topLevel);
void emitClass(Emitter& e, ClassScopePtr cNode, bool topLevel);
void emitTypedef(Emitter& e, TypedefStatementPtr);
void emitForeachListAssignment(Emitter& e,
ListAssignmentPtr la,
int vLocalId);
void emitForeach(Emitter& e, ForEachStatementPtr fe);
void emitRestoreErrorReporting(Emitter& e, Id oldLevelLoc);
void emitMakeUnitFatal(Emitter& e, const std::string& message);
void emitMakeUnitFatal(Emitter& e,
const char* msg,
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);
@@ -683,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,
+124 -106
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,28 +27,26 @@
#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"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/include_expression.h"
#include "hphp/compiler/expression/user_attribute.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
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,
@@ -193,13 +222,6 @@ int FileScope::getGlobalAttribute() const {
return m_attributes.back();
}
bool FileScope::needPseudoMainVariables() const {
VariableTablePtr variables = m_pseudoMain->getVariables();
return
variables->getAttribute(VariableTable::ContainsDynamicVariable) ||
variables->getSymbols().size() > 0;
}
///////////////////////////////////////////////////////////////////////////////
ExpressionPtr FileScope::getEffectiveImpl(AnalysisResultConstPtr ar) const {
@@ -240,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) {
@@ -307,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);
}
@@ -395,12 +418,15 @@ 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(), "", st, 0, "",
ExpressionListPtr()));
ExpressionListPtr(), TypeAnnotationPtr(),
st, 0, "", ExpressionListPtr()));
f->setFileLevel();
FunctionScopePtr pseudoMain(
new HPHP::FunctionScope(ar, true,
@@ -432,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());
}
@@ -457,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);
}
}
@@ -493,3 +510,4 @@ void FileScope::serialize(JSON::DocTarget::OutputStream &out) const {
ms.done();
}
}
+22 -23
Ver Arquivo
@@ -17,15 +17,17 @@
#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/runtime/base/md5.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,7 +145,12 @@ public:
const std::string &decname);
void addClassAlias(const std::string& target, const std::string& alias) {
m_classAliasMap.insert(std::make_pair(target, alias));
m_classAliasMap.insert(
std::make_pair(
boost::to_lower_copy(target),
boost::to_lower_copy(alias)
)
);
}
std::multimap<std::string,std::string> const& getClassAliases() const {
@@ -146,7 +158,7 @@ public:
}
void addTypeAliasName(const std::string& name) {
m_typeAliasNames.insert(name);
m_typeAliasNames.insert(boost::to_lower_copy(name));
}
std::set<std::string> const& getTypeAliasNames() const {
@@ -161,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);
@@ -180,32 +190,22 @@ public:
const std::string &pseudoMainName();
void outputFileCPP(AnalysisResultPtr ar, CodeGenerator &cg);
bool load();
bool needPseudoMainVariables() const;
std::string outputFilebase() const;
void addPseudoMainVariable(const std::string &name) {
m_pseudoMainVariables.insert(name);
}
std::set<std::string> &getPseudoMainVariables() {
return m_pseudoMainVariables;
}
FunctionScopeRawPtr getPseudoMain() const {
return m_pseudoMain;
}
FileScopePtr shared_from_this() {
return boost::static_pointer_cast<FileScope>
return static_pointer_cast<FileScope>
(BlockScope::shared_from_this());
}
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;
@@ -217,7 +217,6 @@ private:
vertex_descriptor m_vertex;
std::string m_pseudoMainName;
std::set<std::string> m_pseudoMainVariables;
BlockScopeSet m_providedDefs;
std::set<std::string> m_redecBases;
+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);
+71 -78
Ver Arquivo
@@ -33,12 +33,12 @@
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/util/atomic.h"
#include "hphp/util/util.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/variable_serializer.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/type-conversions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/runtime/base/zend-string.h"
using namespace HPHP;
@@ -58,15 +58,17 @@ FunctionScope::FunctionScope(AnalysisResultConstPtr ar, bool method,
m_method(method), m_refReturn(reference), m_virtual(false),
m_hasOverride(false), m_perfectVirtual(false), m_overriding(false),
m_volatile(false), m_persistent(false), m_pseudoMain(inPseudoMain),
m_magicMethod(false), m_system(false), m_inlineable(false), m_sep(false),
m_magicMethod(false), m_system(false), m_inlineable(false),
m_containsThis(false), m_containsBareThis(0), m_nrvoFix(true),
m_inlineAsExpr(false), m_inlineSameContext(false),
m_contextSensitive(false),
m_directInvoke(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_generator(false),
m_async(false),
m_noLSB(false), m_nextLSB(false),
m_hasTry(false), m_hasGoto(false), m_localRedeclaring(false),
m_redeclaring(-1), m_inlineIndex(0), m_optFunction(0), m_nextID(0),
m_yieldLabelCount(0) {
m_yieldLabelCount(0), m_yieldLabelGen(-1) {
init(ar);
for (unsigned i = 0; i < attrs.size(); ++i) {
if (m_userAttributes.find(attrs[i]->getName()) != m_userAttributes.end()) {
@@ -89,7 +91,8 @@ FunctionScope::FunctionScope(FunctionScopePtr orig,
const string &name,
const string &originalName,
StatementPtr stmt,
ModifierExpressionPtr modifiers)
ModifierExpressionPtr modifiers,
bool user)
: BlockScope(name, orig->m_docComment, stmt,
BlockScope::FunctionScope),
m_minParam(orig->m_minParam), m_maxParam(orig->m_maxParam),
@@ -101,19 +104,22 @@ FunctionScope::FunctionScope(FunctionScopePtr orig,
m_overriding(orig->m_overriding), m_volatile(orig->m_volatile),
m_persistent(orig->m_persistent),
m_pseudoMain(orig->m_pseudoMain), m_magicMethod(orig->m_magicMethod),
m_system(orig->m_system), m_inlineable(orig->m_inlineable),
m_sep(orig->m_sep), m_containsThis(orig->m_containsThis),
m_system(!user), m_inlineable(orig->m_inlineable),
m_containsThis(orig->m_containsThis),
m_containsBareThis(orig->m_containsBareThis), m_nrvoFix(orig->m_nrvoFix),
m_inlineAsExpr(orig->m_inlineAsExpr),
m_inlineSameContext(orig->m_inlineSameContext),
m_contextSensitive(orig->m_contextSensitive),
m_directInvoke(orig->m_directInvoke),
m_closureGenerator(orig->m_closureGenerator), m_noLSB(orig->m_noLSB),
m_generator(orig->m_generator),
m_async(orig->m_async),
m_noLSB(orig->m_noLSB),
m_nextLSB(orig->m_nextLSB), m_hasTry(orig->m_hasTry),
m_hasGoto(orig->m_hasGoto), m_localRedeclaring(orig->m_localRedeclaring),
m_redeclaring(orig->m_redeclaring),
m_inlineIndex(orig->m_inlineIndex), m_optFunction(orig->m_optFunction),
m_nextID(0), m_yieldLabelCount(orig->m_yieldLabelCount) {
m_nextID(0), m_yieldLabelCount(orig->m_yieldLabelCount),
m_yieldLabelGen(orig->m_yieldLabelGen) {
init(ar);
m_originalName = originalName;
setParamCounts(ar, m_minParam, m_maxParam);
@@ -202,12 +208,14 @@ FunctionScope::FunctionScope(bool method, const std::string &name,
m_method(method), m_refReturn(reference), m_virtual(false),
m_hasOverride(false), m_perfectVirtual(false), m_overriding(false),
m_volatile(false), m_persistent(false), m_pseudoMain(false),
m_magicMethod(false), m_system(true), m_inlineable(false), m_sep(false),
m_magicMethod(false), m_system(true), m_inlineable(false),
m_containsThis(false), m_containsBareThis(0), m_nrvoFix(true),
m_inlineAsExpr(false), m_inlineSameContext(false),
m_contextSensitive(false),
m_directInvoke(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_generator(false),
m_async(false),
m_noLSB(false), m_nextLSB(false),
m_hasTry(false), m_hasGoto(false), m_localRedeclaring(false),
m_redeclaring(-1), m_inlineIndex(0),
m_optFunction(0) {
@@ -279,6 +287,15 @@ void FunctionScope::setParamSpecs(AnalysisResultPtr ar) {
}
}
bool FunctionScope::hasUserAttr(const char *attr) const {
return m_userAttributes.find(attr) != m_userAttributes.end();
}
bool FunctionScope::isZendParamMode() const {
return m_attributeClassInfo &
(ClassInfo::ZendParamModeNull | ClassInfo::ZendParamModeFalse);
}
bool FunctionScope::isPublic() const {
return m_modifiers && m_modifiers->isPublic();
}
@@ -299,6 +316,10 @@ bool FunctionScope::isAbstract() const {
return m_modifiers && m_modifiers->isAbstract();
}
bool FunctionScope::isNative() const {
return hasUserAttr("__native");
}
bool FunctionScope::isFinal() const {
return m_modifiers && m_modifiers->isFinal();
}
@@ -334,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());
@@ -343,35 +369,24 @@ bool FunctionScope::isClosure() const {
return ParserBase::IsClosureName(name());
}
bool FunctionScope::isGenerator() const {
assert(!getOrigGenStmt() ||
(ParserBase::IsContinuationName(name()) &&
m_paramNames.size() == 1 &&
m_paramNames[0] == CONTINUATION_OBJECT_NAME));
return !!getOrigGenStmt();
int FunctionScope::allocYieldLabel() {
assert(m_yieldLabelGen >= 0);
return ++m_yieldLabelCount;
}
bool FunctionScope::hasGeneratorAsBody() const {
MethodStatementPtr stmt = dynamic_pointer_cast<MethodStatement>(getStmt());
return stmt ? !!stmt->getGeneratorFunc() : false;
int FunctionScope::getYieldLabelCount() const {
assert(m_yieldLabelGen >= 0);
return m_yieldLabelCount;
}
bool FunctionScope::isGeneratorFromClosure() const {
bool res = isGenerator() && getOrigGenFS()->isClosure();
assert(!res || getOrigGenFS()->isClosureGenerator());
return res;
int FunctionScope::getYieldLabelGeneration() const {
assert(m_yieldLabelGen >= 0);
return m_yieldLabelGen;
}
MethodStatementRawPtr FunctionScope::getOrigGenStmt() const {
if (!getStmt()) return MethodStatementRawPtr();
MethodStatementPtr m =
dynamic_pointer_cast<MethodStatement>(getStmt());
return m ? m->getOrigGeneratorFunc() : MethodStatementRawPtr();
}
FunctionScopeRawPtr FunctionScope::getOrigGenFS() const {
MethodStatementRawPtr origStmt = getOrigGenStmt();
return origStmt ? origStmt->getFunctionScope() : FunctionScopeRawPtr();
void FunctionScope::resetYieldLabelCount() {
++m_yieldLabelGen;
m_yieldLabelCount = 0;
}
void FunctionScope::setVariableArgument(int reference) {
@@ -530,6 +545,7 @@ bool FunctionScope::mayUseVV() const {
return (inPseudoMain() ||
isVariableArgument() ||
isGenerator() ||
isAsync() ||
variables->getAttribute(VariableTable::ContainsDynamicVariable) ||
variables->getAttribute(VariableTable::ContainsExtract) ||
variables->getAttribute(VariableTable::ContainsCompact) ||
@@ -655,7 +671,8 @@ int FunctionScope::inferParamTypes(AnalysisResultPtr ar, ConstructPtr exp,
/**
* Duplicate the logic of getParamType(i), w/o the mutation
*/
TypePtr paramType(i < m_maxParam ? m_paramTypes[i] : TypePtr());
TypePtr paramType(i < m_maxParam && !isZendParamMode() ?
m_paramTypes[i] : TypePtr());
if (!paramType) paramType = Type::Some;
if (valid && !canSetParamType && i < m_maxParam &&
(!Option::HardTypeHints || !m_paramTypeSpecs[i])) {
@@ -667,8 +684,8 @@ int FunctionScope::inferParamTypes(AnalysisResultPtr ar, ConstructPtr exp,
* expression since it'll just get converted anyways. Doing it this way
* allows us to generate less temporaries along the way.
*/
TypePtr optParamType(
paramType->is(Type::KindOfVariant) ? Type::Some : paramType);
TypePtr optParamType(paramType->is(Type::KindOfVariant) ?
Type::Some : paramType);
expType = param->inferAndCheck(ar, optParamType, false);
} else {
expType = param->inferAndCheck(ar, Type::Some, false);
@@ -775,15 +792,10 @@ void FunctionScope::setParamName(int index, const std::string &name) {
void FunctionScope::setParamDefault(int index, const char* value, int64_t len,
const std::string &text) {
assert(index >= 0 && index < (int)m_paramNames.size());
auto sd = StringData::GetStaticString(value, len);
m_paramDefaults[index] = String(sd);
m_paramDefaults[index] = std::string(value, len);
m_paramDefaultTexts[index] = text;
}
CStrRef FunctionScope::getParamDefault(int index) {
return m_paramDefaults[index];
}
void FunctionScope::addModifier(int mod) {
if (!m_modifiers) {
m_modifiers =
@@ -836,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;
@@ -849,7 +864,7 @@ bool FunctionScope::popReturnType() {
m_prevReturn.reset();
addUpdates(UseKindCallerReturn);
#ifdef HPHP_INSTRUMENT_TYPE_INF
atomic_inc(RescheduleException::s_NumRetTypesChanged);
++RescheduleException::s_NumRetTypesChanged;
#endif /* HPHP_INSTRUMENT_TYPE_INF */
return true;
}
@@ -923,28 +938,6 @@ std::string FunctionScope::getDocFullName() const {
return docName;
}
std::string FunctionScope::getInjectionId() const {
string injectionName = CodeGenerator::FormatLabel(getOriginalName());
MethodStatementPtr stmt =
dynamic_pointer_cast<MethodStatement>(getStmt());
assert(stmt);
if (stmt->getGeneratorFunc()) {
injectionName = isClosureGenerator() ?
injectionName :
injectionName + "{continuation}";
} else if (stmt->getOrigGeneratorFunc() &&
!getOrigGenFS()->isClosure()) {
injectionName = CodeGenerator::FormatLabel(
stmt->getOrigGeneratorFunc()->getOriginalName());
}
if (m_redeclaring < 0) {
return injectionName;
}
const string &redecSuffix = string(Option::IdPrefix) +
boost::lexical_cast<std::string>(m_redeclaring);
return injectionName + redecSuffix;
}
///////////////////////////////////////////////////////////////////////////////
void FunctionScope::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
@@ -1070,7 +1063,7 @@ bool FunctionScope::needsAnonClosureClass(ParameterExpressionPtrVec &useVars) {
useVars.clear();
if (!isClosure()) return false;
ParameterExpressionPtrIdxPairVec useVars0;
getClosureUseVars(useVars0, !m_closureGenerator);
getClosureUseVars(useVars0, !m_generator && !m_async);
useVars.resize(useVars0.size());
// C++ seems to be unable to infer the type here on pair_first_elem
transform(useVars0.begin(),
@@ -1084,7 +1077,7 @@ bool FunctionScope::needsAnonClosureClass(
ParameterExpressionPtrIdxPairVec &useVars) {
useVars.clear();
if (!isClosure()) return false;
getClosureUseVars(useVars, !m_closureGenerator);
getClosureUseVars(useVars, !m_generator && !m_async);
return useVars.size() > 0 || getVariables()->hasStaticLocals();
}
+28 -26
Ver Arquivo
@@ -20,9 +20,10 @@
#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/parser/parser.h"
#include "hphp/util/hash-map-typedefs.h"
#include "hphp/parser/parser.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -73,7 +74,7 @@ public:
FunctionScope(FunctionScopePtr orig, AnalysisResultConstPtr ar,
const std::string &name, const std::string &originalName,
StatementPtr stmt, ModifierExpressionPtr modifiers);
StatementPtr stmt, ModifierExpressionPtr modifiers, bool user);
/**
* System functions.
@@ -84,22 +85,25 @@ public:
void setParamName(int index, const std::string &name);
void setParamDefault(int index, const char* value, int64_t len,
const std::string &text);
CStrRef getParamDefault(int index);
void setRefParam(int index);
bool hasRefParam(int max) const;
void addModifier(int mod);
bool hasUserAttr(const char *attr) const;
/**
* What kind of function this is.
*/
bool isUserFunction() const { return !m_system;}
bool isUserFunction() const { return !m_system && !isNative(); }
bool isSystem() const { return m_system; }
bool isDynamic() const { return m_dynamic; }
bool isPublic() const;
bool isProtected() const;
bool isPrivate() const;
bool isStatic() const;
bool isAbstract() const;
bool isNative() const;
bool isFinal() const;
bool isMagic() const;
bool isRefParam(int index) const;
@@ -109,20 +113,18 @@ public:
bool hasImpl() const;
void setDirectInvoke() { m_directInvoke = true; }
bool hasDirectInvoke() const { return m_directInvoke; }
bool isZendParamMode() const;
bool mayContainThis();
bool isClosure() const;
bool isGenerator() const;
bool isGeneratorFromClosure() const;
int allocYieldLabel() { return ++m_yieldLabelCount; }
int getYieldLabelCount() const { return m_yieldLabelCount; }
bool hasGeneratorAsBody() const;
MethodStatementRawPtr getOrigGenStmt() const;
FunctionScopeRawPtr getOrigGenFS() const;
void setClosureGenerator() { m_closureGenerator = true; }
bool isClosureGenerator() const {
assert(!m_closureGenerator || isClosure());
return m_closureGenerator;
}
bool isGenerator() const { return m_generator; }
void setGenerator(bool f) { m_generator = f; }
int allocYieldLabel();
int getYieldLabelCount() const;
int getYieldLabelGeneration() const;
void resetYieldLabelCount();
bool isAsync() const { return m_async; }
void setAsync(bool f) { m_async = f; }
bool needsClassParam();
void setInlineSameContext(bool f) { m_inlineSameContext = f; }
@@ -158,7 +160,6 @@ public:
}
virtual std::string getId() const;
std::string getInjectionId() const;
int getRedeclaringId() const {
return m_redeclaring;
@@ -227,6 +228,8 @@ public:
bool allowOverride() const;
void setAllowOverride();
bool needsFinallyLocals() const;
/**
* Whether this function is a runtime helper function
*/
@@ -254,6 +257,8 @@ public:
/**
* What is the inferred type of this function's return.
* Note that for generators and async functions, this is different
* from what caller actually gets when calling the function.
*/
void pushReturnType();
void setReturnType(AnalysisResultConstPtr ar, TypePtr type);
@@ -308,10 +313,6 @@ public:
bool isInlined() const { return m_inlineable; }
void disableInline() { m_inlineable = false; }
/* Whether this function is brought in by a separable extension */
void setSepExtension() { m_sep = true;}
bool isSepExtension() const { return m_sep;}
/* Whether we need to worry about the named return value optimization
for this function */
void setNRVOFix(bool flag) { m_nrvoFix = flag; }
@@ -388,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);
@@ -440,7 +441,7 @@ private:
std::vector<std::string> m_paramNames;
TypePtrVec m_paramTypes;
TypePtrVec m_paramTypeSpecs;
std::vector<String> m_paramDefaults;
std::vector<std::string> m_paramDefaults;
std::vector<std::string> m_paramDefaultTexts;
std::vector<bool> m_refs;
TypePtr m_returnType;
@@ -463,7 +464,6 @@ private:
unsigned m_magicMethod : 1;
unsigned m_system : 1;
unsigned m_inlineable : 1;
unsigned m_sep : 1;
unsigned m_containsThis : 1; // contains a usage of $this?
unsigned m_containsBareThis : 2; // $this outside object-context,
// 2 if in reference context
@@ -472,7 +472,8 @@ private:
unsigned m_inlineSameContext : 1;
unsigned m_contextSensitive : 1;
unsigned m_directInvoke : 1;
unsigned m_closureGenerator : 1;
unsigned m_generator : 1;
unsigned m_async : 1;
unsigned m_noLSB : 1;
unsigned m_nextLSB : 1;
unsigned m_hasTry : 1;
@@ -489,6 +490,7 @@ private:
ReadWriteMutex m_inlineMutex;
unsigned m_nextID; // used when cloning generators for traits
int m_yieldLabelCount; // number of allocated yield labels
int m_yieldLabelGen; // generation counter for yield labels
std::list<FunctionScopeRawPtr> m_clonedTraitOuterScope;
};
+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
+5 -4
Ver Arquivo
@@ -14,9 +14,10 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/live_dict.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/expression.h"
@@ -465,7 +466,6 @@ bool LiveDict::color(TypePtr type) {
if (sym &&
!sym->isGlobal() &&
!sym->isParameter() &&
!sym->isGeneratorParameter() &&
!sym->isClosureVar() &&
!sym->isStatic() &&
!e->isThis()) {
@@ -610,7 +610,7 @@ public:
SimpleVariablePtr sv(static_pointer_cast<SimpleVariable>(e));
Symbol *sym = sv->getSymbol();
if (!sym || sym->isGlobal() || sym->isStatic() || sym->isParameter() ||
sym->isGeneratorParameter() || sym->isClosureVar() || sv->isThis()) {
sym->isClosureVar() || sv->isThis()) {
continue;
}
@@ -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:
+17 -17
Ver Arquivo
@@ -14,9 +14,9 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
@@ -29,7 +29,7 @@
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
using std::vector;
@@ -74,10 +74,10 @@ void RefDict::visit(ExpressionPtr e) {
SimpleVariablePtr ptr(static_pointer_cast<SimpleVariable>(e));
if (ptr->isSuperGlobal() || ptr->isThis()) {
// don't both recording for super globals or this
// don't both recording for super globals or this
return;
}
// Good to go
if (m_am.insertForDict(e)) {
record(e);
@@ -129,7 +129,7 @@ void RefDict::updateParams() {
bool isRef;
if (sym->isParameter()) {
ExpressionListPtr methodParams = m_method_stmt->getParams();
ExpressionPtr paramExprPtr =
ExpressionPtr paramExprPtr =
(*methodParams)[sym->getParameterIndex()];
paramType = paramExprPtr->getType();
isRef = m_method_stmt->isRef(sym->getParameterIndex());
@@ -160,7 +160,7 @@ void RefDict::updateParams() {
void RefDict::updateAccess(ExpressionPtr e) {
always_assert(!e->getScope()->inPseudoMain());
int eid = e->getCanonID();
int context = e->getContext();
@@ -204,7 +204,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
context & Expression::UnsetContext) {
BitOps::set_bit(eid, m_referenced, false);
BitOps::set_bit(eid, m_killed, true);
}
}
if (first_pass) return;
@@ -215,7 +215,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
// we dealt with this node as a store expression
return;
}
int cls = e->getExprClass();
bool isRhsNeeded = false;
@@ -227,7 +227,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
if (cls & Expression::Store) {
// we care about two cases here
switch (e->getKindOf()) {
case Expression::KindOfAssignmentExpression:
case Expression::KindOfAssignmentExpression:
// $x = ...
{
AssignmentExpressionPtr assign(
@@ -254,7 +254,7 @@ void RefDict::updateAccess(ExpressionPtr e) {
break;
}
}
bool isLhsSimpleVar = false;
bool isLhsDynamic = false;
bool isRefd = false;
@@ -343,20 +343,20 @@ void RefDict::updateAccess(ExpressionPtr e) {
// unset($x);
BitOps::set_bit(eid, m_obj, false);
BitOps::set_bit(eid, m_noobj, true);
} else if (isRefd ||
} else if (isRefd ||
((context & Expression::Declaration) == Expression::Declaration)) {
// if a simple variable has isRefd, then we need to mark it
// as potentially containing an object.
// also, if the simple variable is in global context
// also, if the simple variable is in global context
// then we also mark it as potentially containing an object
BitOps::set_bit(eid, m_obj, true);
BitOps::set_bit(eid, m_noobj, false);
}
}
}
if (isRefd) {
// do a scan for every simple variable referenced value
// in the dictionary and mark it as potentially
// do a scan for every simple variable referenced value
// in the dictionary and mark it as potentially
// containing an object (in the bit vector)
for (int i = size(); i--; ) {
if (ExpressionPtr e = get(i)) {
@@ -372,8 +372,8 @@ void RefDict::updateAccess(ExpressionPtr e) {
}
int RefDictWalker::after(ConstructRawPtr cp) {
if (SimpleVariableRawPtr s =
boost::dynamic_pointer_cast<SimpleVariable>(cp)) {
if (SimpleVariableRawPtr s =
dynamic_pointer_cast<SimpleVariable>(cp)) {
if (int id = s->getCanonID()) {
if (first_pass) {
if (s->isAvailable() && m_block->getBit(DataFlow::PRefIn, id)) {
+5 -16
Ver Arquivo
@@ -27,9 +27,9 @@
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/variable_serializer.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/util/logger.h"
@@ -65,13 +65,13 @@ TypePtr Symbol::setType(AnalysisResultConstPtr ar, BlockScopeRawPtr scope,
// at this point, you *must* have a lock (if you are user scope)
if (scope->is(BlockScope::FunctionScope)) {
FunctionScopeRawPtr f =
boost::static_pointer_cast<FunctionScope>(scope);
static_pointer_cast<FunctionScope>(scope);
if (f->isUserFunction()) {
f->getInferTypesMutex().assertOwnedBySelf();
}
} else if (scope->is(BlockScope::ClassScope)) {
ClassScopeRawPtr c =
boost::static_pointer_cast<ClassScope>(scope);
static_pointer_cast<ClassScope>(scope);
if (c->isUserClass()) {
c->getInferTypesMutex().assertOwnedBySelf();
}
@@ -520,17 +520,6 @@ ConstructPtr SymbolTable::getValue(const std::string &name) const {
return ConstructPtr();
}
void SymbolTable::setSepExtension(const std::string &name) {
genSymbol(name, m_const)->setSep();
}
bool SymbolTable::isSepExtension(const std::string &name) const {
if (const Symbol *sym = getSymbol(name)) {
return sym->isSep();
}
return false;
}
TypePtr SymbolTable::setType(AnalysisResultConstPtr ar, const std::string &name,
TypePtr type, bool coerced) {
return setType(ar, genSymbol(name, m_const), type, coerced);
+5 -17
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);
@@ -74,9 +75,7 @@ public:
void setReplaced() { m_flags.m_replaced = true; }
bool valueSet() const { return m_flags.m_value_set; }
bool isSystem() const { return m_flags.m_system; }
bool isSep() const { return m_flags.m_sep; }
void setSystem() { m_flags.m_system = true; }
void setSep() { m_flags.m_sep = true; }
bool isConstant() const { return m_flags.m_constant; }
void setConstant() { m_flags.m_constant = true; }
@@ -115,8 +114,6 @@ public:
bool isIndirectAltered() const { return m_flags.m_indirectAltered; }
bool isReferenced() const { return !m_flags.m_notReferenced; }
bool isHidden() const { return m_flags.m_hidden; }
bool isGeneratorParameter() const { return m_flags.m_generatorParameter; }
bool isRefGeneratorParameter() const { return m_flags.m_refGeneratorParameter; }
bool isClosureVar() const { return m_flags.m_closureVar; }
bool isRefClosureVar() const { return m_flags.m_refClosureVar; }
bool isPassClosureVar() const { return m_flags.m_passClosureVar; }
@@ -142,8 +139,6 @@ public:
void setIndirectAltered() { m_flags.m_indirectAltered = true; }
void setReferenced() { m_flags.m_notReferenced = false; }
void setHidden() { m_flags.m_hidden = true; }
void setGeneratorParameter() { m_flags.m_generatorParameter = true; }
void setRefGeneratorParameter() { m_flags.m_refGeneratorParameter = true; }
void setClosureVar() { m_flags.m_closureVar = true; }
void setRefClosureVar() { m_flags.m_refClosureVar = true; }
void setPassClosureVar() { m_flags.m_passClosureVar = true; }
@@ -189,7 +184,7 @@ private:
std::string m_name;
unsigned int m_hash;
union {
uint64_t m_flags_val;
uint32_t m_flags_val;
struct {
/* internal */
unsigned m_declaration_set : 1;
@@ -200,7 +195,6 @@ private:
/* common */
unsigned m_system : 1;
unsigned m_sep : 1;
/* ConstantTable */
unsigned m_dynamic : 1;
@@ -223,8 +217,6 @@ private:
unsigned m_indirectAltered : 1;
unsigned m_notReferenced : 1;
unsigned m_hidden : 1;
unsigned m_generatorParameter : 1;
unsigned m_refGeneratorParameter : 1;
unsigned m_closureVar : 1;
unsigned m_refClosureVar : 1;
unsigned m_passClosureVar : 1;
@@ -281,7 +273,7 @@ private:
/**
* Base class of VariableTable and ConstantTable.
*/
class SymbolTable : public boost::enable_shared_from_this<SymbolTable>,
class SymbolTable : public std::enable_shared_from_this<SymbolTable>,
public JSON::CodeError::ISerializable {
public:
static Mutex AllSymbolTablesMutex;
@@ -347,10 +339,6 @@ public:
ConstructPtr getDeclaration(const std::string &name) const;
ConstructPtr getValue(const std::string &name) const;
/* Whether this constant is brought in by a separable extension */
void setSepExtension(const std::string &name);
bool isSepExtension(const std::string &name) const;
/**
* How big of a hash table for generate C++ switch statements.
*/
+34 -7
Ver Arquivo
@@ -20,7 +20,8 @@
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/vm/runtime.h"
#include <boost/format.hpp>
using namespace HPHP;
@@ -36,6 +37,7 @@ TypePtr Type::Double (new Type(Type::KindOfDouble ));
TypePtr Type::String (new Type(Type::KindOfString ));
TypePtr Type::Array (new Type(Type::KindOfArray ));
TypePtr Type::Object (new Type(Type::KindOfObject ));
TypePtr Type::Resource (new Type(Type::KindOfResource ));
TypePtr Type::Variant (new Type(Type::KindOfVariant ));
TypePtr Type::Numeric (new Type(Type::KindOfNumeric ));
@@ -57,6 +59,8 @@ void Type::InitTypeHintMap() {
assert(s_HHTypeHintTypes.empty());
s_TypeHintTypes["array"] = Type::Array;
s_TypeHintTypes["resource"] = Type::Resource;
s_TypeHintTypes["callable"] = Type::Variant;
s_HHTypeHintTypes["array"] = Type::Array;
s_HHTypeHintTypes["bool"] = Type::Boolean;
@@ -67,6 +71,10 @@ 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;
}
const Type::TypePtrMap &Type::GetTypeHintTypes(bool hhType) {
@@ -79,9 +87,12 @@ void Type::ResetTypeHintTypes() {
}
TypePtr Type::CreateObjectType(const std::string &clsname) {
// For interfaces that support arrays we're pessimistic and
// For interfaces that support primitive types, we're pessimistic and
// we treat it as a Variant
if (interface_supports_array(clsname)) {
if (interface_supports_array(clsname) ||
interface_supports_string(clsname) ||
interface_supports_int(clsname) ||
interface_supports_double(clsname)) {
return Type::Variant;
}
return TypePtr(new Type(KindOfObject, clsname));
@@ -90,9 +101,12 @@ TypePtr Type::CreateObjectType(const std::string &clsname) {
TypePtr Type::GetType(KindOf kindOf, const std::string &clsname /* = "" */) {
assert(kindOf);
if (!clsname.empty()) {
// For interfaces that support arrays we're pessimistic and
// For interfaces that support primitive types we're pessimistic and
// we treat it as a Variant
if (interface_supports_array(clsname)) {
if (interface_supports_array(clsname) ||
interface_supports_string(clsname) ||
interface_supports_int(clsname) ||
interface_supports_double(clsname)) {
return Type::Variant;
}
return TypePtr(new Type(kindOf, clsname));
@@ -107,6 +121,7 @@ TypePtr Type::GetType(KindOf kindOf, const std::string &clsname /* = "" */) {
case KindOfArray: return Type::Array;
case KindOfVariant: return Type::Variant;
case KindOfObject: return Type::Object;
case KindOfResource: return Type::Resource;
case KindOfNumeric: return Type::Numeric;
case KindOfPrimitive: return Type::Primitive;
case KindOfPlusOperand: return Type::PlusOperand;
@@ -193,6 +208,7 @@ bool Type::IsMappedToVariant(TypePtr t) {
case KindOfString :
case KindOfArray :
case KindOfObject :
case KindOfResource:
return false;
default: break;
}
@@ -261,7 +277,8 @@ TypePtr Type::Coerce(AnalysisResultConstPtr ar, TypePtr type1, TypePtr type2) {
if (type1->m_kindOf == KindOfVoid &&
(type2->m_kindOf == KindOfString ||
type2->m_kindOf == KindOfArray ||
type2->m_kindOf == KindOfObject)) {
type2->m_kindOf == KindOfObject ||
type2->m_kindOf == KindOfResource)) {
return type2;
}
if (type2->m_kindOf == KindOfSome ||
@@ -396,6 +413,7 @@ bool Type::HasFastCastMethod(TypePtr t) {
case Type::KindOfString:
case Type::KindOfArray:
case Type::KindOfObject:
case Type::KindOfResource:
return true;
default: break;
}
@@ -441,6 +459,9 @@ string Type::GetFastCastMethod(
case Type::KindOfObject:
type = "Obj";
break;
case Type::KindOfResource:
type = "Res";
break;
default:
type = ""; // make the compiler happy
assert(false);
@@ -536,11 +557,13 @@ bool Type::isSpecificObject() const {
}
bool Type::isNonConvertibleType() const {
return m_kindOf == KindOfObject || m_kindOf == KindOfArray;
return m_kindOf == KindOfObject || m_kindOf == KindOfResource ||
m_kindOf == KindOfArray;
}
bool Type::isNoObjectInvolved() const {
if (couldBe(KindOfObject)
|| couldBe(KindOfResource)
|| couldBe(KindOfArray))
return false;
else
@@ -614,6 +637,7 @@ DataType Type::getDataType() const {
case KindOfString: return HPHP::KindOfString;
case KindOfArray: return HPHP::KindOfArray;
case KindOfObject: return HPHP::KindOfObject;
case KindOfResource: return HPHP::KindOfResource;
case KindOfNumeric:
case KindOfPrimitive:
case KindOfPlusOperand:
@@ -635,6 +659,7 @@ std::string Type::getPHPName() {
switch (m_kindOf) {
case KindOfArray: return "array";
case KindOfObject: return m_name;
case KindOfResource: return "resource";
default: break;
}
return "";
@@ -652,6 +677,7 @@ std::string Type::toString() const {
case KindOfSome: return "Some";
case KindOfAny: return "Any";
case KindOfObject: return string("Object - ") + m_name;
case KindOfResource: return "Resource";
case KindOfNumeric: return "Numeric";
case KindOfPrimitive: return "Primitive";
case KindOfPlusOperand: return "PlusOperand";
@@ -700,6 +726,7 @@ void Type::serialize(JSON::DocTarget::OutputStream &out) const {
}
break;
}
case KindOfResource: s = "resource"; break;
case KindOfNumeric: s = "numeric"; break;
case KindOfPrimitive: s = "primitive"; break;
case KindOfPlusOperand: s = "any"; break;
+4 -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"
@@ -53,6 +53,7 @@ public:
static const KindOf KindOfString = 0x0080;
static const KindOf KindOfArray = 0x0100;
static const KindOf KindOfObject = 0x0200; // with classname
static const KindOf KindOfResource = 0x0400;
static const KindOf KindOfVariant = 0xFFFF;
/* This bit tells coerce that if the other type
@@ -88,6 +89,7 @@ public:
static TypePtr String;
static TypePtr Array;
static TypePtr Object;
static TypePtr Resource;
static TypePtr Variant;
static TypePtr Numeric;
+29 -17
Ver Arquivo
@@ -27,11 +27,12 @@
#include "hphp/compiler/option.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/static_member_expression.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/util/util.h"
#include "hphp/util/parser/location.h"
#include "hphp/util/parser/parser.h"
#include "hphp/parser/location.h"
#include "hphp/parser/parser.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -68,20 +69,31 @@ VariableTable::VariableTable(BlockScope &blockScope)
void VariableTable::getLocalVariableNames(vector<string> &syms) const {
FunctionScopeRawPtr fs = getScopePtr()->getContainingFunction();
bool dollarThisIsSpecial = (fs->getContainingClass() ||
fs->inPseudoMain());
bool dollarThisIsSpecial = fs->getContainingClass() ||
fs->inPseudoMain() ||
// In closures, $this is "sometimes"
// special (if it's a closure in a method
// body), but it easiest to just always
// treat it special.
fs->isClosure();
bool hadThisSym = false;
for (unsigned int i = 0; i < m_symbolVec.size(); i++) {
const string& name = m_symbolVec[i]->getName();
if (name == "this" && dollarThisIsSpecial) {
// The "this" variable in methods and pseudo-main is special and is
// handled separately below.
/*
* The "this" variable in methods, pseudo-main, or closures is
* special and is handled separately below.
*
* Closures are the specialest.
*/
hadThisSym = true;
continue;
}
syms.push_back(name);
}
if (fs->needsLocalThis()) {
if (fs->needsLocalThis() || (hadThisSym && fs->isClosure())) {
assert(dollarThisIsSpecial);
// We only need a local variable named "this" if the current function
// contains an occurrence of "$this" that is not part of a property
@@ -178,8 +190,6 @@ bool VariableTable::isLocal(const Symbol *sym) const {
*/
return (!sym->isStatic() &&
!sym->isGlobal() &&
!sym->isGeneratorParameter() &&
!sym->isRefGeneratorParameter() &&
!sym->isParameter());
}
return false;
@@ -292,8 +302,7 @@ void VariableTable::addStaticVariable(Symbol *sym,
m_hasStatic = true;
FunctionScopeRawPtr funcScope = getFunctionScope();
if (funcScope &&
(funcScope->isClosure() || funcScope->isGeneratorFromClosure())) {
if (funcScope && funcScope->isClosure()) {
// static variables for closures/closure generators are local to the
// function scope
m_staticLocalsVec.push_back(sym);
@@ -417,7 +426,14 @@ TypePtr VariableTable::add(Symbol *sym, TypePtr type,
}
type = setType(ar, sym, type, true);
sym->setDeclaration(construct);
if (sym->isParameter()) {
auto p = dynamic_pointer_cast<ParameterExpression>(construct);
if (p) {
sym->setDeclaration(construct);
}
} else {
sym->setDeclaration(construct);
}
if (!implicit && m_blockScope.isFirstPass()) {
if (!sym->getValue()) {
@@ -569,10 +585,6 @@ void VariableTable::clearUsed() {
} else {
sym.second.setReferenced();
}
if (sym.second.isRefGeneratorParameter()) {
sym.second.setReferenced();
}
}
}
+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
+72 -139
Ver Arquivo
@@ -27,12 +27,12 @@
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/class_info.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/array/array_iterator.h"
#include "hphp/runtime/base/execution_context.h"
#include "hphp/runtime/base/thread_init_fini.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/array-iterator.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/thread-init-fini.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.h"
#include <dlfcn.h>
@@ -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;
///////////////////////////////////////////////////////////////////////////////
@@ -109,12 +103,20 @@ static TypePtr typePtrFromDataType(DataType dt, TypePtr unknown) {
case KindOfString: return Type::String;
case KindOfArray: return Type::Array;
case KindOfObject: return Type::Object;
case KindOfResource: return Type::Resource;
case KindOfUnknown:
default:
return unknown;
}
}
const StaticString
s_fb_call_user_func_safe("fb_call_user_func_safe"),
s_fb_call_user_func_safe_return("fb_call_user_func_safe_return"),
s_fb_call_user_func_array_safe("fb_call_user_func_array_safe"),
s_is_callable("is_callable"),
s_call_user_func_array("call_user_func_array");
FunctionScopePtr BuiltinSymbols::ImportFunctionScopePtr(AnalysisResultPtr ar,
ClassInfo *cls, ClassInfo::MethodInfo *method) {
int attrs = method->attribute;
@@ -155,19 +157,17 @@ FunctionScopePtr BuiltinSymbols::ImportFunctionScopePtr(AnalysisResultPtr ar,
}
f->setClassInfoAttribute(attrs);
if (attrs & ClassInfo::HasDocComment) {
f->setDocComment(method->docComment);
}
f->setDocComment(method->docComment);
if (!isMethod && (attrs & ClassInfo::HasOptFunction)) {
// Legacy optimization functions
if (method->name.same("fb_call_user_func_safe") ||
method->name.same("fb_call_user_func_safe_return") ||
method->name.same("fb_call_user_func_array_safe")) {
if (method->name.same(s_fb_call_user_func_safe) ||
method->name.same(s_fb_call_user_func_safe_return) ||
method->name.same(s_fb_call_user_func_array_safe)) {
f->setOptFunction(hphp_opt_fb_call_user_func);
} else if (method->name.same("is_callable")) {
} else if (method->name.same(s_is_callable)) {
f->setOptFunction(hphp_opt_is_callable);
} else if (method->name.same("call_user_func_array")) {
} else if (method->name.same(s_call_user_func_array)) {
f->setOptFunction(hphp_opt_call_user_func);
}
}
@@ -212,19 +212,22 @@ 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) {
if (((*it)->attribute & ClassInfo::ZendCompat) &&
!Option::EnableZendCompat) {
continue;
}
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);
@@ -263,7 +266,7 @@ void BuiltinSymbols::ImportExtConstants(AnalysisResultPtr ar,
for (auto it = src.begin(); it != src.end(); ++it) {
// We make an assumption that if the constant is a callback type
// (e.g. STDIN, STDOUT, STDERR) then it will return an Object.
// And that if it's deferred (SID, PHP_SAPI) it'll be a String.
// And that if it's deferred (SID, PHP_SAPI, etc.) it'll be a String.
ClassInfo::ConstantInfo *cinfo = *it;
dest->add(cinfo->name.data(),
cinfo->isDeferred() ?
@@ -276,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();
@@ -298,9 +301,7 @@ ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
ImportExtConstants(ar, cl->getConstants(), cls);
int attrs = cls->getAttribute();
cl->setClassInfoAttribute(attrs);
if (attrs & ClassInfo::HasDocComment) {
cl->setDocComment(cls->getDocComment());
}
cl->setDocComment(cls->getDocComment());
cl->setSystem();
return cl;
}
@@ -308,9 +309,15 @@ ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
void BuiltinSymbols::ImportExtClasses(AnalysisResultPtr ar) {
const ClassInfo::ClassMap &classes = ClassInfo::GetClassesMap();
for (auto it = classes.begin(); it != classes.end(); ++it) {
const ClassInfo *info = it->second;
if ((info->getAttribute() & ClassInfo::ZendCompat) &&
!Option::EnableZendCompat) {
continue;
}
ClassScopePtr cl = ImportClassScopePtr(ar, it->second);
assert(!s_classes[cl->getName()]);
s_classes[cl->getName()] = cl;
ar->addSystemClass(cl);
}
}
@@ -322,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();
@@ -337,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 :
@@ -349,119 +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, "SID", true);
s_constants->setDynamic(ar, "PHP_SAPI", 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;
+9 -24
Ver Arquivo
@@ -18,22 +18,23 @@
#define incl_HPHP_BUILTIN_SYMBOLS_H_
#include "hphp/compiler/hphp.h"
#include "hphp/util/string_bag.h"
#include "hphp/runtime/base/class_info.h"
#include "hphp/util/string-bag.h"
#include "hphp/runtime/base/class-info.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
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_
+30 -19
Ver Arquivo
@@ -25,24 +25,24 @@
#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/db-conn.h"
#include "hphp/util/exception.h"
#include "hphp/util/process.h"
#include "hphp/util/util.h"
#include "hphp/util/timer.h"
#include "hphp/util/hdf.h"
#include "hphp/util/async_func.h"
#include "hphp/runtime/base/program_functions.h"
#include "hphp/runtime/base/memory/smart_allocator.h"
#include "hphp/util/async-func.h"
#include "hphp/util/current-executable.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/externals.h"
#include "hphp/runtime/base/thread_init_fini.h"
#include "hphp/runtime/base/thread-init-fini.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/system/systemlib.h"
#include "hphp/util/repo_schema.h"
#include "hphp/util/repo-schema.h"
#include "hphp/hhvm/process_init.h"
#include "hphp/hhvm/process-init.h"
#include <sys/types.h>
#include <sys/wait.h>
@@ -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,8 +358,8 @@ 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";
#include "../version"
#define HHVM_VERSION(v) cout << HPHP_COMPILER_STR #v << "\n";
#include "../version" // nolint
cout << "Compiler: " << kCompilerId << "\n";
cout << "Repo schema: " << kRepoSchemaId << "\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,10 +807,12 @@ 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";
RuntimeOption::EnableHipHopSyntax = Option::EnableHipHopSyntax;
RuntimeOption::EnableZendCompat = Option::EnableZendCompat;
RuntimeOption::EvalJitEnableRenameFunction = Option::JitEnableRenameFunction;
// Turn off commits, because we don't want systemlib to get included
@@ -866,11 +875,11 @@ int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
*/
string exe = po.outputDir + '/' + po.program;
string repo = "repo=" + exe + ".hhbc";
char buf[PATH_MAX];
if (!realpath("/proc/self/exe", buf)) return -1;
string buf = current_executable_path();
if (buf.empty()) return -1;
const char *argv[] = { "objcopy", "--add-section", repo.c_str(),
buf, exe.c_str(), 0 };
buf.c_str(), exe.c_str(), 0 };
string out;
ret = Process::Exec(argv[0], argv, nullptr, out, nullptr) ? 0 : 1;
}
@@ -909,11 +918,13 @@ int runTarget(const CompilerOptions &po) {
// run the executable
string cmd;
if (po.format.find("exe") == string::npos) {
char buf[PATH_MAX];
if (!realpath("/proc/self/exe", buf)) return -1;
string buf = current_executable_path();
if (buf.empty()) return -1;
cmd += buf;
cmd += " -vRepo.Authoritative=true";
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;
+17 -3
Ver Arquivo
@@ -44,7 +44,7 @@ void Construct::resetScope(BlockScopeRawPtr scope, bool resetOrigScope) {
setBlockScope(scope);
if (resetOrigScope) {
ExpressionPtr expr =
boost::dynamic_pointer_cast<Expression>(shared_from_this());
dynamic_pointer_cast<Expression>(shared_from_this());
if (expr) {
expr->setOriginalScope(scope);
}
@@ -439,7 +439,7 @@ public:
// HACK: dump the closure function as a "child" of the
// closure expression
ClosureExpressionPtr c =
boost::dynamic_pointer_cast<ClosureExpression>(cp);
dynamic_pointer_cast<ClosureExpression>(cp);
if (c) {
c->getClosureFunction()->dump(m_spc, m_ar);
}
@@ -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());
}
+14 -6
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"
@@ -67,7 +67,7 @@ public:
/**
* Base class of Expression and Statement.
*/
class Construct : public boost::enable_shared_from_this<Construct>,
class Construct : public std::enable_shared_from_this<Construct>,
public JSON::CodeError::ISerializable {
protected:
Construct(BlockScopePtr scope, LocationPtr loc);
@@ -180,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;
@@ -187,15 +189,16 @@ public:
virtual bool kidUnused(int i) const { return false; }
template<typename T>
static boost::shared_ptr<T> Clone(boost::shared_ptr<T> constr) {
static std::shared_ptr<T> Clone(std::shared_ptr<T> constr) {
if (constr) {
return boost::dynamic_pointer_cast<T>(constr->clone());
return dynamic_pointer_cast<T>(constr->clone());
}
return boost::shared_ptr<T>();
return std::shared_ptr<T>();
}
template<typename T>
boost::shared_ptr<T> Clone(boost::shared_ptr<T> constr, BlockScopePtr scope) {
std::shared_ptr<T> Clone(std::shared_ptr<T> constr,
BlockScopePtr scope) {
if (constr) {
constr = constr->clone();
constr->resetScope(scope);
@@ -243,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.
*/
@@ -19,12 +19,13 @@
#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"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -217,10 +218,10 @@ int ArrayElementExpression::getKidCount() const {
void ArrayElementExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_variable = boost::dynamic_pointer_cast<Expression>(cp);
m_variable = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_offset = boost::dynamic_pointer_cast<Expression>(cp);
m_offset = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -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,7 +17,8 @@
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -94,10 +95,10 @@ int ArrayPairExpression::getKidCount() const {
void ArrayPairExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_name = boost::dynamic_pointer_cast<Expression>(cp);
m_name = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_value = boost::dynamic_pointer_cast<Expression>(cp);
m_value = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -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
@@ -25,15 +25,16 @@
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -160,10 +161,10 @@ int AssignmentExpression::getKidCount() const {
void AssignmentExpression::setNthKid(int n, ConstructPtr cp) {
switch (m_rhsFirst ? 1 - n : n) {
case 0:
m_variable = boost::dynamic_pointer_cast<Expression>(cp);
m_variable = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_value = boost::dynamic_pointer_cast<Expression>(cp);
m_value = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -180,11 +181,11 @@ bool AssignmentExpression::isSimpleGlobalAssign(StringData **name,
Variant v;
if (!m_value->getScalarValue(v) || v.is(KindOfArray)) return false;
if (name) {
*name = StringData::GetStaticString(ae->getGlobalName());
*name = makeStaticString(ae->getGlobalName());
}
if (tv) {
if (v.isString()) {
v = StringData::GetStaticString(v.toCStrRef().get());
v = makeStaticString(v.toCStrRef().get());
}
*tv = *v.asTypedValue();
}
@@ -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
+105
Ver Arquivo
@@ -0,0 +1,105 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/await_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/code_model_enums.h"
using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
AwaitExpression::AwaitExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr exp)
: Expression(EXPRESSION_CONSTRUCTOR_PARAMETER_VALUES(AwaitExpression)),
m_exp(exp), m_label(this) {
}
ExpressionPtr AwaitExpression::clone() {
AwaitExpressionPtr exp(new AwaitExpression(*this));
Expression::deepCopy(exp);
exp->m_exp = Clone(m_exp);
exp->m_label.setExpression(exp.get());
return exp;
}
///////////////////////////////////////////////////////////////////////////////
// parser functions
///////////////////////////////////////////////////////////////////////////////
// static analysis functions
void AwaitExpression::analyzeProgram(AnalysisResultPtr ar) {
assert(getFunctionScope() && getFunctionScope()->isAsync());
m_exp->analyzeProgram(ar);
m_label.setNew();
}
ConstructPtr AwaitExpression::getNthKid(int n) const {
switch (n) {
case 0:
return m_exp;
default:
assert(false);
break;
}
return ConstructPtr();
}
int AwaitExpression::getKidCount() const {
return 1;
}
void AwaitExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
break;
}
}
TypePtr AwaitExpression::inferTypes(AnalysisResultPtr ar, TypePtr type,
bool coerce) {
m_exp->inferAndCheck(ar, Type::Some, false);
return Type::Variant;
}
///////////////////////////////////////////////////////////////////////////////
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
void AwaitExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
cg_printf("await ");
m_exp->outputPHP(cg, ar);
}
+46
Ver Arquivo
@@ -0,0 +1,46 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_AWAIT_EXPRESSION_H_
#define incl_HPHP_AWAIT_EXPRESSION_H_
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/generation_label.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(AwaitExpression);
class AwaitExpression : public Expression {
public:
AwaitExpression(EXPRESSION_CONSTRUCTOR_PARAMETERS,
ExpressionPtr exp);
DECLARE_EXPRESSION_VIRTUAL_FUNCTIONS;
ExpressionPtr getExpression() { return m_exp; }
GenerationLabel& label() { return m_label; }
private:
ExpressionPtr m_exp;
GenerationLabel m_label;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_AWAIT_EXPRESSION_H_
+117 -18
Ver Arquivo
@@ -18,20 +18,22 @@
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/runtime/base/complex_types.h"
#include "hphp/runtime/base/type_conversions.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/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"
#include "hphp/runtime/base/comparisons.h"
#include "hphp/runtime/base/zend/zend_string.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/encaps_list_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/statement/loop_statement.h"
#include "hphp/runtime/base/tv_arith.h"
#include "hphp/runtime/base/tv-arith.h"
#include "hphp/runtime/vm/runtime.h"
using namespace HPHP;
@@ -65,17 +67,22 @@ 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) {
} else if (strcasecmp(s.c_str(), "map") == 0 ||
strcasecmp(s.c_str(), "stablemmap") == 0) {
cType = Collection::MapType;
} else if (strcasecmp(s.c_str(), "stablemap") == 0) {
cType = Collection::StableMapType;
} else if (strcasecmp(s.c_str(), "set") == 0) {
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);
@@ -243,10 +250,10 @@ int BinaryOpExpression::getKidCount() const {
void BinaryOpExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp1 = boost::dynamic_pointer_cast<Expression>(cp);
m_exp1 = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_exp2 = boost::dynamic_pointer_cast<Expression>(cp);
m_exp2 = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -476,6 +483,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 +546,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:
@@ -598,10 +611,27 @@ ExpressionPtr BinaryOpExpression::foldConst(AnalysisResultConstPtr ar) {
case T_LOGICAL_AND:
result = v1.toBoolean() && v2.toBoolean(); break;
case T_INSTANCEOF: {
if (v1.isArray() && v2.isString() &&
interface_supports_array(v2.getStringData())) {
result = true;
break;
if (v2.isString()) {
if (v1.isArray() &&
interface_supports_array(v2.getStringData())) {
result = true;
break;
}
if (v1.isString() &&
interface_supports_string(v2.getStringData())) {
result = true;
break;
}
if (v1.isInteger() &&
interface_supports_int(v2.getStringData())) {
result = true;
break;
}
if (v1.isDouble() &&
interface_supports_double(v2.getStringData())) {
result = true;
break;
}
}
result = false;
break;
@@ -785,7 +815,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);
@@ -894,6 +924,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
@@ -974,4 +1074,3 @@ bool BinaryOpExpression::isOpEqual() {
}
return false;
}
@@ -108,7 +108,7 @@ int ClassConstantExpression::getKidCount() const {
void ClassConstantExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_class = boost::dynamic_pointer_cast<Expression>(cp);
m_class = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -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;
+204 -108
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,73 +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 (param->getName() == "this") {
// "this" is automatically included.
// Once we get rid of all the callsites, make this an error
continue;
}
if (seenBefore.find(param->getName().c_str()) == seenBefore.end()) {
seenBefore.insert(param->getName().c_str());
m_vars->insertElement(param);
}
}
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() {
@@ -124,7 +133,7 @@ int ClosureExpression::getKidCount() const {
void ClosureExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_values = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_values = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
@@ -137,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,
@@ -256,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);
@@ -284,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
@@ -296,3 +390,5 @@ void ClosureExpression::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) {
}
m_func->outputPHPBody(cg, ar);
}
}
+38 -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;
@@ -40,16 +51,38 @@ public:
FunctionStatementPtr getClosureFunction() { return m_func; }
ExpressionListPtr getClosureVariables() { return m_vars; }
ExpressionListPtr getClosureValues() { return m_values; }
StringData* getClosureClassName() { return m_closureClassName; }
void setClosureClassName(StringData* value) { m_closureClassName = value; }
bool hasStaticLocals();
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;
static TypePtr s_ClosureType;
bool hasStaticLocalsImpl(ConstructPtr root);
StringData* m_closureClassName;
std::set<std::string> m_unboundNames;
CaptureState m_captureState;
};
///////////////////////////////////////////////////////////////////////////////
+12 -1
Ver Arquivo
@@ -26,7 +26,7 @@
#include "hphp/util/util.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/runtime/ext/ext_misc.h"
@@ -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
@@ -78,13 +78,18 @@ ExpressionPtr DynamicFunctionCall::preOptimize(AnalysisResultConstPtr ar) {
if (m_nameExp->getScalarValue(v) &&
v.isString()) {
string name = v.toString().c_str();
ExpressionPtr cls = m_class;
if (!cls && !m_className.empty()) {
cls = makeScalarExpression(ar, m_className);
// if the name starts with a '\' give up any early optimizations and
// let FPushFunc manage the namespace normalizations at runtime
// (some static analyzer may still be able to optimize it - e.g. HHBBC)
if (name[0] != '\\') {
ExpressionPtr cls = m_class;
if (!cls && !m_className.empty()) {
cls = makeScalarExpression(ar, m_className);
}
return ExpressionPtr(NewSimpleFunctionCall(
getScope(), getLocation(),
name, false, m_params, cls));
}
return ExpressionPtr(NewSimpleFunctionCall(
getScope(), getLocation(),
name, false, m_params, cls));
}
}
return ExpressionPtr();
@@ -113,6 +118,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) {
+15 -1
Ver Arquivo
@@ -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;
@@ -66,7 +67,7 @@ int DynamicVariable::getKidCount() const {
void DynamicVariable::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exp = boost::dynamic_pointer_cast<Expression>(cp);
m_exp = dynamic_pointer_cast<Expression>(cp);
break;
default:
assert(false);
@@ -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
@@ -18,7 +18,7 @@
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/runtime/base/builtin_functions.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -70,7 +70,7 @@ int EncapsListExpression::getKidCount() const {
void EncapsListExpression::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_exps = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_exps = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
@@ -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
+12 -3
Ver Arquivo
@@ -17,7 +17,7 @@
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
#include "hphp/util/util.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
@@ -30,12 +30,13 @@
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/object_property_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/function_call.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/util/hash.h"
#include "hphp/runtime/base/array/array_iterator.h"
#include "hphp/runtime/base/array-iterator.h"
using namespace HPHP;
@@ -368,7 +369,7 @@ void Expression::setTypes(AnalysisResultConstPtr ar, TypePtr actualType,
}
if (m_actualType->isSpecificObject()) {
boost::const_pointer_cast<AnalysisResult>(ar)->
std::const_pointer_cast<AnalysisResult>(ar)->
addClassDependency(getFileScope(), m_actualType->getName());
}
}
@@ -674,6 +675,14 @@ bool Expression::isArray() const {
return false;
}
bool Expression::isCollection() const {
if (is(KindOfBinaryOpExpression)) {
return
static_cast<const BinaryOpExpression*>(this)->getOp() == T_COLLECTION;
}
return false;
}
bool Expression::isUnquotedScalar() const {
if (!is(KindOfScalarExpression)) return false;
return !((ScalarExpression*)this)->isQuoted();
+22 -3
Ver Arquivo
@@ -17,6 +17,8 @@
#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"
@@ -36,6 +38,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 +50,7 @@ namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
DECLARE_BOOST_TYPES(Statement);
DECLARE_BOOST_TYPES(Expression);
DECLARE_EXTENDED_BOOST_TYPES(Expression);
class Variant;
#define DECLARE_EXPRESSION_TYPES(x) \
@@ -76,7 +79,18 @@ class Variant;
x(EncapsListExpression, None), \
x(ClosureExpression, None), \
x(YieldExpression, None), \
x(UserAttribute, None)
x(AwaitExpression, 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:
@@ -202,7 +216,7 @@ public:
*/
virtual int getKidCount() const { return 0; }
ExpressionPtr getNthExpr(int n) const { return
boost::static_pointer_cast<Expression>(getNthKid(n)); }
static_pointer_cast<Expression>(getNthKid(n)); }
/**
* For cse & canonicalization
@@ -232,6 +246,7 @@ public:
virtual bool isTemporary() const { return false; }
virtual bool isScalar() const { return false; }
bool isArray() const;
bool isCollection() const;
virtual bool isRefable(bool checkError = false) const { return false; }
virtual bool getScalarValue(Variant &value) { return false; }
FileScopeRawPtr getUsedScalarScope(CodeGenerator& cg);
@@ -347,6 +362,10 @@ public:
return isNoRemove() && m_assertedType;
}
virtual bool allowCellByRef() const {
return false;
}
static ExpressionPtr MakeConstant(AnalysisResultConstPtr ar,
BlockScopePtr scope,
LocationPtr loc,
+23 -23
Ver Arquivo
@@ -22,7 +22,7 @@
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/runtime/base/array/array_init.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/compiler/parser/parser.h"
using namespace HPHP;
@@ -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) {
}
@@ -231,37 +230,26 @@ void ExpressionList::stripConcat() {
for (int i = 0; i < el.getCount(); ) {
ExpressionPtr &e = el[i];
if (e->is(Expression::KindOfUnaryOpExpression)) {
UnaryOpExpressionPtr u(boost::static_pointer_cast<UnaryOpExpression>(e));
UnaryOpExpressionPtr u(static_pointer_cast<UnaryOpExpression>(e));
if (u->getOp() == '(') {
e = u->getExpression();
}
}
if (e->is(Expression::KindOfBinaryOpExpression)) {
BinaryOpExpressionPtr b
(boost::static_pointer_cast<BinaryOpExpression>(e));
(static_pointer_cast<BinaryOpExpression>(e));
if (b->getOp() == '.') {
e = b->getExp1();
el.insertElement(b->getExp2(), i + 1);
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;
}
@@ -335,7 +323,7 @@ void ExpressionList::setNthKid(int n, ConstructPtr cp) {
if (n >= m) {
assert(false);
} else {
m_exps[n] = boost::dynamic_pointer_cast<Expression>(cp);
m_exps[n] = dynamic_pointer_cast<Expression>(cp);
}
}
@@ -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;
+45 -32
Ver Arquivo
@@ -35,7 +35,7 @@
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/util/parser/hphp.tab.hpp"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -120,13 +120,13 @@ int FunctionCall::getKidCount() const {
void FunctionCall::setNthKid(int n, ConstructPtr cp) {
switch (n) {
case 0:
m_class = boost::dynamic_pointer_cast<Expression>(cp);
m_class = dynamic_pointer_cast<Expression>(cp);
break;
case 1:
m_nameExp = boost::dynamic_pointer_cast<Expression>(cp);
m_nameExp = dynamic_pointer_cast<Expression>(cp);
break;
case 2:
m_params = boost::dynamic_pointer_cast<ExpressionList>(cp);
m_params = dynamic_pointer_cast<ExpressionList>(cp);
break;
default:
assert(false);
@@ -171,39 +171,43 @@ void FunctionCall::markRefParams(FunctionScopePtr func,
}
}
void FunctionCall::checkParamTypeCodeErrors(AnalysisResultPtr ar) {
if (!m_funcScope || m_arrayParams) return;
for (int i = 0, n = m_funcScope->getMaxParamCount(); i < n; ++i) {
TypePtr specType = m_funcScope->getParamTypeSpec(i);
if (!specType) continue;
const char *fmt = 0;
string ptype;
if (!m_params || m_params->getCount() <= i) {
if (i >= m_funcScope->getMinParamCount()) break;
fmt = "parameter %d of %s() requires %s, none given";
} else {
ExpressionPtr param = (*m_params)[i];
if (!Type::Inferred(ar, param->getType(), specType)) {
fmt = "parameter %d of %s() requires %s, called with %s";
}
ptype = param->getType()->toString();
}
if (fmt) {
string msg;
Util::string_printf
(msg, fmt,
i + 1,
Util::escapeStringForCPP(m_funcScope->getOriginalName()).c_str(),
specType->toString().c_str(), ptype.c_str());
Compiler::Error(Compiler::BadArgumentType,
shared_from_this(), msg);
}
}
}
void FunctionCall::analyzeProgram(AnalysisResultPtr ar) {
if (m_class) m_class->analyzeProgram(ar);
if (m_nameExp) m_nameExp->analyzeProgram(ar);
if (m_params) m_params->analyzeProgram(ar);
if (ar->getPhase() == AnalysisResult::AnalyzeFinal) {
if (m_funcScope && !m_arrayParams) {
for (int i = 0, n = m_funcScope->getMaxParamCount(); i < n; ++i) {
if (TypePtr specType = m_funcScope->getParamTypeSpec(i)) {
const char *fmt = 0;
string ptype;
if (!m_params || m_params->getCount() <= i) {
if (i >= m_funcScope->getMinParamCount()) break;
fmt = "parameter %d of %s() requires %s, none given";
} else {
ExpressionPtr param = (*m_params)[i];
if (!Type::Inferred(ar, param->getType(), specType)) {
fmt = "parameter %d of %s() requires %s, called with %s";
}
ptype = param->getType()->toString();
}
if (fmt) {
string msg;
Util::string_printf
(msg, fmt,
i + 1,
Util::escapeStringForCPP(m_funcScope->getOriginalName()).c_str(),
specType->toString().c_str(), ptype.c_str());
Compiler::Error(Compiler::BadArgumentType,
shared_from_this(), msg);
}
}
}
}
checkParamTypeCodeErrors(ar);
}
}
@@ -545,6 +549,15 @@ TypePtr FunctionCall::checkParamsAndReturn(AnalysisResultPtr ar,
assert(!func->inVisitScopes() || getScope() == func);
frt = func->getReturnType();
}
// fix return type for generators and async functions here, keep the
// infered return type in function scope to allow further optimizations
if (func->isGenerator()) {
frt = Type::GetType(Type::KindOfObject, "Continuation");
} else if (func->isAsync()) {
frt = Type::GetType(Type::KindOfObject, "WaitHandle");
}
if (!frt) {
m_voidReturn = true;
setActualType(TypePtr());
+3
Ver Arquivo
@@ -65,6 +65,9 @@ public:
bool isValid() const { return m_valid; }
bool hadBackslash() const { return m_hadBackslash; }
private:
void checkParamTypeCodeErrors(AnalysisResultPtr);
protected:
ExpressionPtr m_nameExp;
std::string m_name;
@@ -0,0 +1,49 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/expression/generation_label.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/expression.h"
namespace HPHP {
GenerationLabel::GenerationLabel(Expression* e)
: m_id(-1)
, m_generation(-1)
, m_owner(e)
{}
int GenerationLabel::id() const {
assert(m_id >= 1);
assert(m_generation ==
m_owner->getFunctionScope()->getYieldLabelGeneration());
return m_id;
}
void GenerationLabel::setNew() {
auto func = m_owner->getFunctionScope();
auto newGen = func->getYieldLabelGeneration();
assert(m_generation < newGen);
m_generation = newGen;
m_id = func->allocYieldLabel();
}
void GenerationLabel::setExpression(Expression* e) {
m_owner = e;
}
}
+40
Ver Arquivo
@@ -0,0 +1,40 @@
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_COMPILER_GENERATION_LABEL_H
#define incl_HPHP_COMPILER_GENERATION_LABEL_H
namespace HPHP {
class Expression;
class GenerationLabel {
public:
explicit GenerationLabel(Expression* e);
int id() const;
void setNew();
void setExpression(Expression* e);
private:
int m_id;
int m_generation;
Expression* m_owner;
};
}
#endif
+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_

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais