3994 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
Sara Golemon ee8da60efa Releasing HipHop 2.1.0 2013-07-12 11:00:55 -07:00
Sean Cannella 61d58af783 fix compilation on Ubuntu 13.04
- missing inline generates warnings on Ubuntu which seems to
make compiler very unhappy

Closes #848
2013-07-11 17:25:02 -07:00
Sara Golemon b010c70f17 Bump gcc required version to 4.6.0 2013-07-11 17:16:13 -07:00
Sara Golemon 86b00778e3 Add skeleton.sh script for making extension skeletons from idl.json files 2013-07-11 16:00:06 -07:00
Jordan DeLong 9584995bec Fix (disable) reporting of extended typehints via reflection
Right now (on trunk, not release), a function with a ?int
typehint tells the reflection API its typehint is just "int".  For
now, just turn this off.  (If we want this later we'll probably have
to add a new API or something?)
2013-07-11 15:12:09 -07:00
Jordan DeLong da32bc9d88 Turn off extended type hint checks 2013-07-11 15:12:06 -07:00
Eric Caruso fa04bcb180 Trace declared instance properties of objects
Instance properties were being completely ignored,
so the heap graph was missing a lot of information.
2013-07-11 15:11:13 -07:00
Eric Caruso b94ab7709f Translate FPushFuncU
We were punting on this, but it's a pretty easy
translation, and it makes calling functions from inside namespaces
much faster.

Closes #814
2013-07-11 15:11:13 -07:00
Sara Golemon a2139988d0 Update url_raw_encode() to ignore '~' characters
Per Bug#53248, tilde characters should
not be encoded.
2013-07-11 15:11:12 -07:00
mwilliams 47970e99d7 Fix url rewriting
Only apply pathTranslation if a path hasn't been rewritten
(they're always relative paths), or if the rewritten path
didn't begin with '/'.
2013-07-11 15:11:12 -07:00
Sara Golemon ca02e9e482 Update php_base64_decode() to cover Bug52327
Strict mode should fail on padding characters mid-stream.
2013-07-11 15:11:12 -07:00
Mike Magruder 3a750ae5ac Add client connect info to the debugger usage log.
Update the connect usage log message to include details of the client that is connecting to a proxy, or to state if it's a connection due to script debugging.
2013-07-11 15:11:12 -07:00
Guilherme Ottoni 244d4da93a Replace _ with - in file names under runtime/vm/jit/
Makes things more consistent, at least within this directory.
2013-07-11 15:11:11 -07:00
mwilliams 01b67654a6 Revert "Fix duplicate HTTP headers"
This reverts commit e265247f34572eedd087ee01c8e43bdab319b322.
2013-07-11 15:11:10 -07:00
Jordan DeLong d2c4442980 Translate some trivial cases of IncDecL
These are easy, so why not.
2013-07-11 15:11:09 -07:00
Jordan DeLong 524cbb5d3e Implement shift operators outside of Variant 2013-07-11 15:11:09 -07:00
Jordan DeLong dec333dd14 Implement most bitwise arithmetic outside of Variant
Everything except unary bitwise not.
2013-07-11 15:11:09 -07:00
Jordan DeLong 049e1d585e Remove Variant unary negation and unary plus @override-unit-failures
These are only used for constant folding in the frontend.
Change stuff to do it there the way we actually implement them at
runtime.
2013-07-11 15:11:09 -07:00
Sara Golemon f9da9970d2 Pass OS determination from CMake into gen-ext-hhvm.sh 2013-07-10 20:25:50 -07:00
Sara Golemon bd88f6bccd Explicitly link libjemalloc into folly 2013-07-10 20:25:50 -07:00
Sara Golemon a2a9f88dd8 Don't double / file paths, it confuses poor CMake 2013-07-10 20:25:50 -07:00
Sara Golemon ccb3060ae9 Test's cpp files are moved to hphp/test/ext
Also create missing test_ext.inc
2013-07-10 20:25:32 -07:00
Guilherme Ottoni b64942b1f3 Move hopt_preparable.php to test/vm-perf
The goal of this benchmark was to measure performance, so increase the
number of iterations and move it out of test/quick.
2013-07-10 12:22:22 -07:00
Daniel Sloof 948040f7d8 OSX changes, next round
- fix merge issues
- remove platform-specific neo defines that were getting pulled in everywhere
- fix asm alignment directive on OSX
2013-07-10 12:22:18 -07:00
bsimmers 5dd304c0f8 Clean up VectorEffects::init
This is my attempt to clean up and simplify the logic in here
a bit. It also fixes a bug that we were hitting in the region
compiler: setting an element of a StaticStr may promote it to a
CountedStr.
2013-07-10 11:16:53 -07:00
Guilherme Ottoni a4c445dbfb Allow JIT-time known boxed types for source operand in cgCheckType
In the region JIT, we may end up with a CheckType on a source with a
known type that is boxed but different from the boxed type parameter
of CheckType.  We still want to keep such CheckType instruction to
communicate the type of its dest to the following code. However, that
instruction doesn't need to generate any code since the inner types
are checked at the uses (via LdRef).
2013-07-10 11:16:53 -07:00
Mike Magruder d1553bda9e Add simple functions to determine if a debugger is attached
Added two simple functions to determine if a debugger is attached, and to provide info about where the debugger is connected from. Also fixed a minor bug in ext_socket where the name for an unbound AF_UNIX socket would come back from getsocketname()/getpeername() as garbage.
2013-07-10 11:16:52 -07:00
bsimmers 182ced3575 Remove operator==(Op, Opcode) and friends
I added them to ease the transition but since Opcode is just
uint8_t, they remove a lot of the safety of making Op an enum class.
2013-07-10 11:16:52 -07:00
Drew Paroski 84b9d9a3a2 Separate resources from objects, part 1
In HHVM (and HPHPc before it) 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 prepares the code base for a new KindOfResource type by adding a
new "Resource" smart pointer type (currently a typedef for the Object smart
pointer type) and it updates the C++ code and the idl files appropriately.
This diff is essentially a cosmetic change and should not impact run time
behavior. In the next diff (part 2) we'll actually add a new KindOfResource
type, detach ResourceData from the ObjectData inheritence hierarchy, and
provide a real implementation for the Resource smart pointer type (instead
of just aliasing the Object smart pointer type).
2013-07-10 11:16:33 -07:00
Edwin Smith 46f2eb82a5 Delete some dead code in NameValueTableWrapper and SharedMap 2013-07-10 11:16:33 -07:00
Alexandru Suhan c330882232 Combine IssetM and EmptyM implementations 2013-07-10 11:16:32 -07:00
Jordan DeLong 6e4e52197e Implement +=, -=, *=, /= and %= outside of Variant 2013-07-10 11:16:32 -07:00
Sean Cannella 9bdd5805b3 More OSX fixes
readelf -> gobjdump
folly exclusions
undef GNU_SOURCE
2013-07-10 09:38:34 -07:00
Paul Saab ac91741c0f Fix duplicate HTTP headers
When the same header is passed in, Apache/PHP will comma delimit
all header values for the returned values in apache_request_headers
and $_SERVER['HTTP_*'].
2013-07-09 13:45:41 -07:00
Guilherme Ottoni 85f3ccbd01 ContSuspendK should break tracelets
It's a control-flow instruction.
2013-07-09 13:45:40 -07:00
Guilherme Ottoni 679c1a2f99 Fix tools/reduce
The runtime option used by this script was renamed. Also, stop
retranslating as soon as JitGlobalTranslationLimit is reached.
2013-07-09 13:45:40 -07:00
Guilherme Ottoni 1a8d77f1db Allow AssertType of Cls
We need this with the region JIT.
2013-07-09 13:45:40 -07:00
Kyle Delong 772c0cef17 Fix native Exception::setPreviousChain() fatal
Fixes a fatal in native Exception, which is missing parentheses on this method call.
2013-07-09 13:45:39 -07:00
Daniel Sloof d71433a966 get HHVM to compile on OSX
This is a squash of https://github.com/danslo/hiphop-php/compare/osx-review
2013-07-09 13:45:35 -07:00
Dario Russi 54b8a31c6f relax guard change to allow for specialized guards
Unified code for relax and specialize guards and removed type propagation on relaxation
2013-07-09 12:24:22 -07:00
Guilherme Ottoni d4c2b60537 Mark CheckType non-CSEable
It's a control-flow instruction, and we don't support eliminating
control-flow yet.

This got exposed by the region/trace JIT.
2013-07-09 12:24:22 -07:00
Sara Golemon f487b96cf8 Move SessionModule class to ext_session's header
So that other extensions can register their own
Session Modules.
2013-07-09 12:24:21 -07:00
Eric Caruso c3d067f65c Optimize InstanceOfD when rhs is unique interface
We would normally have to load the class and do
a whole bunch of other noise. Now we don't.
2013-07-09 12:24:21 -07:00
Sara Golemon 06da48df2d Modify PHP's ext/standard/math/tests/(pow|abs).phpt to be HHVM friendly
HHVM's arithmetic operators do not promote to double.
Use double-casted LONG_MIN/MAX to track this behavior.
2013-07-09 12:24:21 -07:00
Sara Golemon 65e4672ea1 Update folly 2013-07-09 12:20:45 -07:00
Sean Cannella ce9837db9a emitTLSLoad doesn't work on OSX with emulated TLS
- Provide a TLS solution that works on OSX with __emutls_*
2013-07-08 10:30:58 -07:00
mwilliams 795aa1309c Cleanup lifetime management for translation units
For PhpFiles, there was a mixed management system, where references from
translated code were held until the code was made unreachable, while
references from interpreted code were held for the duration of the
current request. Under the new scheme, PhpFiles are always treadmilled.
They are owned by the FileRepository, and so need to be ref-counted
because the FileRepository can have the same PhpFile under multiple
paths. But we don't ref-count the *uses* of PhpFiles anymore.

Classes still need to be ref-counted, but as soon as their Unit
goes away, most of their internals can be freed. We just need to
hold onto them if derived classes are referencing them. Even in
that case, the next time we try to instantiate the derived class,
we can kill any that reference this Class.

There were also lots of holes where references were not dropped,
or owned data structures were not destroyed. eg a Class's methods
were not destroyed when the Class was destroyed; there were
several paths where an entry was erased from the file map, but the
corresponding PhpFile was not decRef'd - or worse, a null entry
was left in the map (something we had asserts to check for).

This tries to make the handling more consistent.
2013-07-08 10:30:58 -07:00
mwilliams f704123389 Retry fsockopen
It only fails very occasionally, so add some retrys

Facbook:

I logged into a contbuild machine where it had failed. 3 out of the 4
runs had actually succeeded. In the one run where it failed,
it was the ssl connection. So I tried running just that 1000 times, and
got no failures. Seems likely that the retries will help.
2013-07-08 10:30:58 -07:00
mwilliams bc5778169e Fix a DateTime leak
D860568 fixed a double free, but introduced a leak. If no
timezone is specified in the input string, timelib_fill_holes
would clone the one from m_time. Since we unconditionally cloned
*that* into m_tz, the clone from timelib_fill_holes was leaked.

The contract seems to be that m_time doesn't own it's tz_info, but
that it should be owned by a smart pointer somewhere. So we can tell
timelib_fill_holes *not* to clone the tz_info from its second parameter,
and at the same time optimize for the usual case where that timezone
is already the current timezone.
2013-07-08 10:30:57 -07:00
Drew Paroski d336b46cc7 Merge ObjectData and Instance together, part 2
When object support was first added to HHVM, a class named "Instance"
was introduced (deriving from ObjectData) to represent instances of user
defined classes. Since then, things have evolved and HPHPc and HPHPi have
been retired, and now there really is no needed to have ObjectData and
Instance be separate classes anymore.

This diff moves all of the functionality from the Instance class to the
ObjectData and removes the Instance class. In the process, I got rid of
a bunch of dead methods and fixed some indentation and other style issues.
2013-07-08 10:30:57 -07:00
Edwin Smith 5b512b77b6 Devirtualize nvGetCell()
ArrayData::nvGetCell was only called from one place in vectortranslator.cpp
so hand-inline it there using nvGet(), which is already virtual.
2013-07-08 10:30:57 -07:00
Drew Paroski 9edc07112b Merge ObjectData and Instance together, part 1
When object support was first added to HHVM, a class named "Instance"
was introduced (deriving from ObjectData) to represent instances of user
defined classes. Since then, things have evolved and HPHPc and HPHPi have
been retired, and now there really is no needed to have ObjectData and
Instance be separate classes anymore.

As a first step towards merging ObjectData and Instance together, this diff
puts their definitions in the same .h file and puts their implementations
in the same .cpp file. A few small changes were necessary to fix issues
with cyclical includes: (1) Repo/emitter related parts of class.cpp and
class.h were moved to class-emit.cpp and class-emit.h; (2) the contents of
"vm/core_types.h" was moved to "base/types.h"; and (3) a few functions that
didn't appear to be hot were moved from .h files and the corresponding .cpp
files.
2013-07-06 11:12:29 -07:00
Edwin Smith 29b1fb3cf0 Consolidate more ArrayData methods: getKey, getValue, and nvGetValueRef
getKey wraps nvGetKey
getValue and nvGetValueRef wrap getValueRef
2013-07-06 11:12:29 -07:00
Jordan DeLong 59b2a173d2 Fix varCopy 2013-07-06 11:12:29 -07:00
Jordan DeLong 7be051d7e6 Check key types for KindOfInt64 instead of using isNumeric 2013-07-06 11:12:29 -07:00
Jordan DeLong 42bab0c57f Remove unused ArrayData param for setWithRefHelper
Mark said this used to do something related to avoiding a
recursive array, but I don't quite understand it and it's unused now.
2013-07-06 11:12:28 -07:00
mwilliams 0b0741103e Set proper timeouts for SSLSocket
If no timeout was specified in fsockopen, we passed in 0.0,
which was then used as the actual timeout, meaning that while the
socket opened, it almost always failed to open in ssl mode due to
timeout, and then read garbage data from the socket.

We also failed to pass in the specified timeout for non-ssl sockets,
but there we did use the default timeout rather than 0.0. I've changed
that to use the passed in timeout instead.
2013-07-06 11:12:28 -07:00
mwilliams 8f6224d194 Fix cfi directives in enterTCHelper
Right now, if you don't have gdb symbols enabled for
jitted code, its impossible to get a backtrace in gdb that
crosses enterTCHelper (I'm not entirely sure why it works when
symbols *are* enabled, but still).

With the .cfi directives brought up to date, a gdb backtrace
walks across enterTCHelper just like any other function.
2013-07-06 11:12:28 -07:00
Paul Bissonnette 0d5d5bca72 Added IterBreakV, MIter{Init,InitK,Next,NextK,Free} and fixed memory tracking bug.
Added IR opcodes to perform MIter* instructions in JIT.  Added IterBreakV bytecode
operation to break out of multiple loops containing iterators.  Emitter and assembler
were modified to support such use.
2013-07-06 11:12:28 -07:00
mwilliams 083b1d32ad Fix SpillStack's argument validation
It was asserting that the input to a SpillStack is
a subtype of one of Gen, Cls or None, rather than subtype of
Gen|Cls or None.

Added a new type Type::StackElem, and used it.
2013-07-06 11:12:27 -07:00
mwilliams fa0d20a58a Don't hang if socket fails to open
feof($f) returns false if $f is invalid, so if the
socket failed to open we spun forever, causing the tests to
eventually timeout. The test will still fail, but at least
we get meaningful results for the rest.
2013-07-06 11:12:27 -07:00
Jordan DeLong 5371743d9d Convert tv_comparisons/tv_conversions by-pointer TypedValue/Cells to by value
If we're not going to mutate the Cell, it might make sense to
pass it by value rather than pointer to const.  Do folks like this
better?  I can see a couple arguments various ways.  But it does seem
like even if we want to pass it by pointer at the hardware level we
would ideally passing by const reference at the language level, so
this choice would be transparent at callsite code.  This diff doesn't
change anything in tv_helpers.h for now.
2013-07-06 11:12:27 -07:00
Kyle Delong 9108d3523d XHP comment syntax
XML comment syntax for XHP is one of the top wishlist items within the UIE group (+ some other people).

Currently, the only way to have comments inside XHP blocks is to use expressions and block comments, e.g.

  <div>{/* comment */}</div>

After this change, you can use the more familiar syntax. This syntax is limited to XHP child contexts:

  // Only single-line, doc, block comments work outside XHP
  $xhp =
    <div>
      <!--XML comments only work within XHP children contexts-->
    </div>;

Based on http://www.w3.org/TR/REC-xml/#sec-comments - except we ignore the rule about double hyphens ('--') within a comment because we don't care about SGML.
2013-07-06 11:12:26 -07:00
Drew Paroski 1ee3810e21 Small cleanup for ObjectData and a few other things
This diff addresses most of the diff review feedback from D740016.
2013-07-06 11:12:24 -07:00
mwilliams 8075c39588 Fix incorrect assert
An assert was recently added that every local in the
origFunc was also a local in the genFunc, but its not necessarily
true. Also fix the usage to not corrupt the ActRec in this case.
2013-07-06 11:12:23 -07:00
mwilliams a61c47e801 Fix refCounts for SetM on strings
When we throw an InvalidSetMException, we need to incRef the value we
throw.
2013-07-06 11:12:23 -07:00
Stephen Chen d4de02ba16 Get rid of Synchronized<hphp_hash_map> from service_data
We can get rid of all the lock contention by using
tbb::concurrent_hash_map. Unfortunately tbb::concurrent_hash_map doesn't let us
iterate over it while we concurrently do inserts. Work around this limitation by
keeping a copy of all the counter keys in a concurrent_vector which does let us
concurrently insert and iterate.

On lookup / insert, we first look into concurrent_hash_map for the key. If key
already exists, return the value. Otherwise, we insert into both the map and the
list.

On export, we iterate over the list and look up each key from the map.
2013-07-06 11:12:23 -07:00
Eric Caruso 6eba57f898 Make func_get_args and friends work with namespaces
func_get_args would only return declared parameters
when used inside of namespaces. This allows it to work correctly
in that case.

Closes #832
2013-07-06 11:12:23 -07:00
Mike Magruder f4bed8899a Initialize all fields of Static{Result|Exception}WaitHandle
We force users to use the create() methods of StaticResultWaitHandle and StaticExceptionWaitHandle, which properly set m_resultOrException. However, deserialization will use the normal constructor which was failing to initialize the field. The destructor, then, would operate on random data. This broke hphpd when a stack trace had one of these objects on it somewhere. The 'where' command would succeed, but the next command (which deletes the stack trace), would segfault in the wait handle's destructor.

I think it's fair to not serialize this member. It's not exposed thru PHP except via joining with the wait handle, and I think an argument can be made that it's just plain wrong to join with a deserialized copy of a wait handle. So I've just initialized it to a reasonable default.
2013-07-06 11:12:22 -07:00
Stephen Chen fd5d218e8e HPHP: Drop the request when it's been sitting on the select queue longer than the virtual host timeout allows for.
Drop the request when it's been sitting on the select queue longer than the
virtual host timeout allows for. This is orthogonal to the expiration timeout on
the queue itself.

This can be useful if we ever allow select queue timeout to be configured to be
higher than the virtual host request timeout.
2013-07-06 11:12:22 -07:00
Stephen Chen bacd44b43f Add runtime options for fb303 server.
Add runtime options for fb303 server. These go into the open source tree, but
masked off by #ifdef FACEBOOK.
2013-07-06 11:12:22 -07:00
Scott MacVicar 14125f4b06 Allow \ in the LHS of the hdf config file.
The autoload_map.hdf doesn't support backslashes when it's on the LHS.
This broke an intern build last week when we pushed out namespace
support for third-party.

Looked like:
```functions {
  GlobalNamespace\Class = flib/intern/third-party/test.php
}```
2013-07-06 11:12:22 -07:00
Dario Russi ef99ac3445 Allow parameter promotion in constructors
Extend PHP to allow constructor paramters to be promoted to fields. Reduce plumbing of class declaration and helps productivity.
2013-07-06 11:12:21 -07:00
Edwin Smith 047ef325bb Consolodate ArrayData position-based iterator methods
Implement these all in ArrayData, using iter_begin, advance,
rewind, and iter_end virtual methods.  Only SharedMap didn't
override the iter_* methods, so moved ArrayData's implementation
to SharedMap and tailored it a bit.  Fetch SharedMap's size at
construction time to avoid calls to SharedMap::vsize().
Removed HphpArray and NameValueTableWrapper implementations of
these methods.
2013-07-06 11:12:18 -07:00
Curran Kaushik 43c35ba61c Scrape logs for information on completely processed HLog files.
First step towards detecting skipping of HLogs. Scrapes the log files in
the directory given by env variable LOGS_HOME and extracts the
timestamp, filename, and final offset from the lines indicating a file
'IS REALLY complete'. Converts to data to JSON to be passed to later
subprocess.
2013-07-06 11:12:18 -07:00
mwilliams b2f7473aeb Fix var_export for resources
Debug builds hit an assert, and release builds would output
something like array(}.
2013-07-06 11:12:17 -07:00
Sean Cannella f0443bba23 more OSX warnings
- fix more OSX warnings
2013-07-06 11:12:17 -07:00
Eric Caruso 24a131117f Improvements to graph dumping in heap trace command
This abstracts the file format a bit, so that we can
dump to multiple formats. Currently, GraphViz and GML are
supported. GML was added at @edwinsmith's request (and it's much
nicer than GraphViz anyway...)
2013-07-06 11:12:17 -07:00
Eric Caruso 5c486012c9 Basic heap tracing framework + debugger command
Adds an extension command to the debugger which provides
heap tracing functionality, and adds the framework needed to get
heap traces. The heaptrace command can dump the current heap to the
debugger session or it can save a GraphViz specification to a file.

I'm hoping to add a backend which can put the graph in GML format,
so it can be explored interactively. I also hope at some point to
see this integrated into FBIDE if we can do that.
2013-07-06 11:12:16 -07:00
Edwin Smith 47b1915f07 Remove dead ArrayData::nvGet() functions.
They were dead.
2013-07-06 11:12:16 -07:00
Eric Caruso 8d85957d57 Fixing OpMod emission not to trigger assert in simplifier
If you tried to mod something where the denominator
was cns(0), things would go horribly, horribly wrong.
2013-07-06 11:12:16 -07:00
Sara Golemon deb3366c27 No need to pass ext/standard/versioning/php_sapi_name_variation001.phpt
The expected output is specific to how PHP implements run-tests
2013-07-06 11:12:16 -07:00
Eric Caruso 0a6e1587e9 Special case some bytecode ops in getStackValue
Some bytecode ops, such as CGetL3, would munch the
types of the things on the stack above the new cell that was
pushed because getStackValue assumes all stack outputs from
interpOne are on top of the stack. The result is that the top
of the stack would contain the output type, and the two things
below it would not get any type (unknown).

This usually isn't a problem, but if we fail enough in type
prediction we might get around to InterpOneing these ops.
2013-07-06 11:12:15 -07:00
Eric Caruso 11dc9d091d Remove problematic VectorTranslator assert
Tried to relax this assert in D871843, but it turns
out the assert is completely unnecessary anyway.
2013-07-06 11:12:15 -07:00
Edwin Smith eb56802c97 Add missing include to fix stacktrace_profiler.h
Broken build fix.
2013-07-06 11:12:15 -07:00
Mike Magruder cb8d51fd2a Enable Ctrl-C while looping only in translated code
The debugger relies on hooks into the interpreter to gain control of threads. If a thread is looping in translated code, though, it will never enter the interpreter. Take advantage of the existing surprise checks emitted on back-branches to pop out of translated code back to the interpreter when trying to interrupt threads due to a Ctrl-C from the client.

Also modified TestDebuggerJit to ensure that the thread executing the infinite loop has time to settle into looping in TC's. The signal to interrupt the server is historically fast enough to get there before one of the translations is made. Added a reasonable delay which caused the test to fail deterministically on my machine before the fix.
2013-07-06 11:12:14 -07:00
Edwin Smith 1532dd8597 Add BoolProfiler and IntProfiler clases (using StackTraceProfiler)
A BoolProfiler uses two StackTraceProfilers to take profiled samples of
a boolean value.  At shutdown it prints the %false, %true, and a profile
for each case.

An IntProfiler is similar, but profiles buckets of 0, 1, 2, 4, and 5+.
2013-07-06 11:12:14 -07:00
Sara Golemon 93f5ec9d67 Don't import tests from php-src:ext/spl/examples
These don't test anything relevent
2013-07-06 11:12:14 -07:00
mwilliams 52b914a4c9 Fix type assertions for array-like interfaces
Without this we could infer that an array was an object,
skip the guards, and then die horribly.
2013-07-06 11:12:14 -07:00
mwilliams db29a1127c Disable code coverage for systemlib.hhas
It has no line number information.
2013-07-02 11:46:28 -07:00
Todd Nowacki 485b0b88b2 Minor Fixes for Clang
While these fixes are mainly for clang, they should (for the most part) prevent possible bugs.

The implicit conversion function has been deleted. The explicit conversion function should be used
~~~hphp/runtime/ext/ext_apc.h
~~~hphp/runtime/ext/ext_domdocument.h
~~~hphp/runtime/ext/ext_hash.h
~~~hphp/runtime/ext/ext_icu_ucnv.h
~~~hphp/runtime/ext/ext_image.h

Char is not standardized to be unsigned, this should be explicit
~~~hphp/runtime/ext/filter/sanitizing_filters.cpp

The C++ Standard does not allow for default arguments in lambdas
~~~hphp/runtime/vm/jit/hhbctranslator.cpp
2013-07-02 11:46:27 -07:00
Stephen Chen 92279b2fc6 HPHP: add mechanism to add hooks around server start.
Add mechanism to add hook around server start. Similar to the existing
Thread/Process Init/Fini hooks. This allows us to add behaviors around the main
hphp server start/stop event without introducing source code level dependency.
2013-07-02 11:46:27 -07:00
Jordan DeLong 361df7eb45 Convert tvSet family to take TypedValues by reference
Turns out I need to use tvSet with temporaries.  Also removes
unused tvSetObject*, and replaces some tvSetNull* callsites with using
make_tv temporaries.
2013-07-02 11:46:27 -07:00
Keith Adams acb01dde5d Make ServiceRequest more flexible.
As part of the relocatable assembly work, I'm going to need to
be able to hook places we burn in values for a*.code.frontier. One of
the more important sets of these places is in the bind* service request
stubs, but the infrastructure surrounding them is all about
undifferentiated constants.

So, add a type-aware layer of translation between the arguments to
emitServiceReq and actual code emission. This solves one code problem
we'd been papering over: needing to transmit the value of the condition
code from the request site in an argument.
2013-07-02 11:46:27 -07:00
Eric Caruso d0e49bb0f0 Add some easy simplifications for OpMod to simplifier
OpMod wasn't doing any constant folding or optimization,
so this might give it a little boost.
2013-07-02 11:46:26 -07:00
mwilliams 74ca5cd27f fb_enable_code_coverage needs an ActRec
It tries to unwind the top, builtin frame, making
various assumptions that aren't true if it was called by
FCallBuiltin. In dbg builds, it asserts.
2013-07-02 11:46:26 -07:00
Guilherme Ottoni bc667596e1 Fix InterpOne's output for predicted types
We were always pushing the output type onto the simulated stack,
effectively passing it as an asserted type, even when the type came
from type prediction.
2013-07-02 11:46:26 -07:00
mwilliams f72684f07a Fix spilling bug in linearscan
If we reload a value in an exit trace that was spilled
in the main trace, a comment tells us that we reload it at the
start of the exit trace. In fact the reload was inserted at the
start of the main trace.

Fixed the code to match the comment.
2013-07-02 11:46:26 -07:00
Mirek Klimos 5a98277b6c Replace ContSend by CGetL+CUnsetL
The behavior of ContSend is equivalent to CGetL+CUnsetL. Let's kill this
unnecessary opcode. Let's remove this logic from ContRaise opcode as
well.
2013-07-02 11:46:25 -07:00
Stephen Chen 50b48f1dab Add an option to allow hphp's request queue dynamically switch between FIFO and LIFO.
Add an option to allow hphp's request queue dynamically switch between FIFO and
LIFO. By default everything is still FIFO like today. Setting
ServerThreadJobLIFO to true turns everything to LIFO like today. If
ServerThreadJobLIFOThreshold is also set, then we do FIFO up until the queue
length hits the threshold. Once the threshold is crossed, workers will take
quests from the end of the queue. Once the queue size shrink below the
threshold, we resume FIFO order.

This behavior helps us prioritize newer requests when the server is loaded.
2013-07-02 11:46:25 -07:00
Herman Venter 959d6b5d3d Test conditional breakpoints and re-enable "called from" breakpoints
Added some test cases. Also now permit caller=>func() type of breakpoints. To make this work, I added a method, getCallingSite, to class InterruptSite and use this to walk the stack when checking if a site matches a break point that has more than one function name.
2013-07-02 11:46:25 -07:00
Alok Menghrajani 7a9769a95b Fix HPHP's parser when handling generics
We need to allow any type after the AS keyword, including xhp class names.
2013-07-02 11:46:25 -07:00
Mike Magruder 0d14e585fd Change TERM when running tests with input
In general, a test which gets its input piped in is not really interacting with a terminal like it normally would. Thus, letting it think it has the same terminal as the environment is incorrect. More specifically, hphpd uses Readline, which inspects the TERM env var and based on that and a stunning array of other options will attempt to initialize the terminal with extra control characters on first use. It would be tough to try to control for all of the different options and ensure they're all the same, and honestly testing Readline is not the objective of our tests anyway. Thus, I'm forcing TERM to 'dumb' when a test has input to ensure a) a simple terminal which requires no control characters and b) consistency no matter what environment is present when the tests are run.
2013-07-02 11:46:21 -07:00
Sara Golemon 556b4ac04f Add EastAsianWidth.txt to checked in files 2013-07-02 00:12:49 -07:00
Sara Golemon 8d839ee730 Remove --arg from travis config
hphp/test/run doesn't seem to know what to do with this anymore
2013-07-01 22:21:15 -07:00
Sara Golemon 8a891f617a Make sure fr_FR locale is available during test 2013-07-01 14:09:17 -07:00
Eric Caruso 5d27fbcc69 Promote cns argument to int64_t to ensure correctness
Some operations such as cns(-1) would end up emitting
the wrong thing, because the -1 literal would be interpreted as
int32_t and only four bytes would get copied across by memcpy.
The result is that cns(-1) would in fact emit the constant
4294967295 (= 2^32-1) which is bound to lead to wrong code.

A former workaround involved using cns(-1LL). I removed this
use case to show that this is now kosher (and added a test to
show that nothing broke - use TRACE=hhir:2 to check).
2013-07-01 13:41:04 -07:00
Sean Cannella b1c329a7e1 annotate a few printf stragglers
- Found a few more va_list functions when reviewing last diff
2013-07-01 13:41:04 -07:00
Bert Maher 8257b2b805 Clean up argument order for AKExists
We were passing the array and key parameters to ak_exist_* in
the opposite order from exists(), leading to some unnecessary register
shuffling.
2013-07-01 13:41:04 -07:00
Stephen Chen 82dc4550da A simple facility to track runtime statistics in hphp.
This a simpler / cleaner version of fbcode's ServiceData for hphp. Currently we
support only flat counters, MultiLevelTimeSeries and Histograms. We can add more
stats types later on as needed.

ServiceData is a global entry point for all this stuff. The current idea is to
completely decouple data input and export. ServiceData internally has three
separate maps tracking flat counters, timeseries and histograms. These maps are
wrapped by spin locks and protected by folly::Synchronized.

ServiceData provides three functions to create/retrive counter objects. The
counter objects are thread safe (protected again by spin locks and
folly::Synchronized).
2013-07-01 13:41:03 -07:00
Avani Nandini e61c684271 Update ext_hash test isFacebook() check 2013-07-01 13:41:03 -07:00
Sean Cannella c891ec4d62 annotate printf-like functions
- added annotations to a few more functions
- fixed a few bugs exposed by the annotations
2013-07-01 13:41:02 -07:00
Jordan DeLong 58d58a10cb Add forgotten expect file 2013-07-01 13:41:02 -07:00
Jordan DeLong 819f3877aa Fix trunk due to merge messup
I apparently merged badly and then committed diffs in a bad
order and broke trunk.
2013-07-01 13:41:02 -07:00
Jordan DeLong 6b92028afd Remove base parameter from tvCastToInt64InPlace
Nothing uses it, and it means we can't as easily drop
folly::to for int-string conversions into these guys, which I'd like
to try later.  (Non-base-10 conversions are probably much rarer so
it's fine to have different code, I think?)

Also removes tvCastToInt64 and ports its single callsite to cellToInt.
I plan to move the tvCastTo*InPlace to tv_conversions.h (probably
cell-based functions) in upcoming diffs.
2013-07-01 13:41:01 -07:00
Jordan DeLong ddfce3150e Fix a crash when dividing INT64_MIN by -1 2013-07-01 13:41:01 -07:00
Jordan DeLong c51583cfb8 Functions for basic php arithmetic operators in tv_arith.h @override-unit-failures
Deletes operator overloads on variant for the same and points
bytecode.cpp at them.  Also fixes one known accidental deviation from
zend.  These functions take Cells by value because it seemed to make
sense---I'll likely convert the various functions in the new
tv_conversions.h (and tv_comparisons.h) to do the same but in another
diff.
2013-07-01 13:41:01 -07:00
Jordan DeLong 8220a18060 Convert a few tvFoo functions to take parameters by reference
Since TypedValue::operator= is dangerous, something like
tvTeleport is usually what you want to use, but it doesn't work with
temporary TypedValues (e.g. return values of things like make_tv or
cellAdd), because it took the arguments by pointer.  This also means
we can change it to take parameters by value later without updating
callsites.  This diff does the tvDup family and changes tvTeleport to
tvCopy.  I'll gradually get the other ones done, but I just need these
for now to work with temporaries for changing SetOp to not use Variant
arithmetic.
2013-07-01 13:41:00 -07:00
Eric Caruso 97a23e5ea7 Support for yield k => v;
Updates continuations to allow yielding of a key-value
pair from a generator. Adds bytecode instructions (PackContK,
ContKey) for using the new feature, and adds IR instructions
(ContUpdateIdx, ContIncKey) to help get it down to the metal
(in particular, ContIncKey attempts to keep the current use-cases
as fast as possible).
2013-07-01 13:41:00 -07:00
Eric Caruso d6fd9de236 Push modular division down to codegen
InterpOne sucks. Let's see if we can do this right.
2013-07-01 13:40:59 -07:00
Drew Paroski e7b90fa691 Clean up how the DebuggerDummyEnv is set up and torn down
A recent diff called my attention to the logic in enterDebuggerDummyEnv()
and exitDebuggerDummyEnv() and I noticed it didn't look quite right.

The first time enterDebuggerDummyEnv() is called it creates a frame on an
empty call stack, but then exitDebuggerDummyEnv() does not correctly tear
down this frame and null out m_fp and m_pc, and this leads to subtle issues.
For example, invokeFunc() checks if m_fp is null to decide whether to call
enterVM() or reenterVM(). I found a case with the "flow_gen_excep.php" test
where invokeFunc was incorrectly calling reenterVM (because m_fp hadn't
been nulled out) and it was pushing bogus VM state info into m_nestedVMs.
This in turn was causing the logic in CmdNext::onBeginInterrupt() to get
confused when comparing the original stack depth with the current stack
depth.

This diff updates exitDebuggerDummyEnv() to correctly tear down the frame
and null out m_fp and m_pc, and it updates enterDebuggerDummyEnv() to
assume the callstack is always empty (which should be the case). I've also
beefed up the asserts in both of these methods.
2013-07-01 13:40:59 -07:00
Eric Caruso c498e390da Make continuations cloneable
Continuations would throw before if you tried to
clone them. This restriction has been lifted.
2013-07-01 13:40:59 -07:00
mwilliams 6bd65a5cd6 Fix spilling bug
If we spilled a FuncCtx (pretty unlikely), we treated the class/this
portion as a type, and only spilled/restored the low 32 bits:

   0xb23ad54:    mov    %r13,0x10(%rsp)
   0xb23ad59:    mov    %edx,0x1c(%rsp) # rdx contained a $this pointer
   0xb23ad5d:    mov    %r14,-0x10(%rbx)
   0xb23ad61:    mov    %r15d,-0x4(%rbx)
   0xb23ad65:    add    $0xfffffffffffffff0,%rbx
   0xb23ad69:    lea    (%rbx),%rdi
   0xb23ad6c:    callq  0x33f68f1 <HPHP::assertTv(HPHP::TypedValue const*)>
   0xb23ad71:    mov    0x10(%rsp),%rdx
   0xb23ad76:    mov    0x1c(%rsp),%ecx # restored here
   0xb23ad7a:    movq   $0x0,-0x8(%rbx)
   0xb23ad82:    mov    %rdx,-0x20(%rbx)
   0xb23ad86:    mov    %rcx,-0x10(%rbx) # and written to the new actrec here
   0xb23ad8a:    mov    %rbp,-0x30(%rbx)
   0xb23ad8e:    movl   $0x0,-0x14(%rbx)
   0xb23ad95:    add    $0xffffffffffffffd0,%rbx
2013-07-01 13:40:58 -07:00
Drew Paroski 900dbd0225 Make HHVM's command line parsing closer to Zend
This diff makes some tweaks to how HHVM handles command line arguments
to match what Zend PHP does. This change will allow developers to type
"hhvm foo.php -x" at the command line and "-x" will get passed as an
argument to the PHP application as it would for Zend PHP.

The basic idea is that we detect the first occurrence of either "--" or a
non-option argument. If we encounter "--" first, all subsequent arguments
are passed along to the PHP application (though the "--" token itself gets
swallowed). If we encounter a non-option argument first, that argument
and everything after it are passed along to the PHP application.
2013-07-01 13:40:58 -07:00
Eric Caruso f377180fcf Small improvements on conversion helpers
Added some asserts, took out some unnecessary checks.
2013-07-01 13:40:57 -07:00
Eric Caruso 3d21090118 Move type dispatch of ConvCellToDbl to simplifier
As D867556, but with doubles.
2013-07-01 13:40:57 -07:00
Drew Paroski 28968640bd Remove bogus assert in bytecode emitter
I hit an array on the debug build when I tried to run the following
program:

  <?php
  function f() {
    for (;;) {}
  }
  f();

This diff removes the offending assert since it is technically possible to
have m_maxStackDepth be equal to 0.
2013-07-01 13:40:57 -07:00
Herman Venter a8749c1618 Remove useless change to test/run
Experimental attempt to make sure test output does not contain non ASCII characters is actually completely useless because it sanitizes an integer. Remove it.
2013-07-01 13:40:56 -07:00
Herman Venter 6adc95a975 Replicate debugger eval tests in test/quick/debugger. Take 2.
Ongoing migration of tests to the new infrastructure. The old tests stay in place until we have another way to test the client API.
2013-07-01 13:40:56 -07:00
mwilliams 60a17c5e24 Fix names of closures in pseudoMains
The classes were all called Closure$, with the result that attempting
to instantiate one closure could instantiate a different one.
2013-07-01 13:40:56 -07:00
Keith Adams a0ae83d0fd Introduce rdtsc, cycle delay primitives.
I keep reintroducing these by hand. My workflow is usually:

1. Have an idea to optimize X.
2. Realize I don't even know if X is important or not.
3. Instrument X to slow it down, to see if it makes a difference in
   perflab.

After this diff, 3 is a simple matter of inserting a call to
cycleDelay(1000) (or what have you) in the path of interest.
2013-07-01 13:40:55 -07:00
Jordan DeLong 652f0e7b2a Remove Variant::swap (unused) because TypedValue::operator= is scary
TypedValue::operator= is potentially dangerous when you don't
know where the TypedValue is actually living.  The reason is it copies
the m_aux from the rhs over the m_aux on the lhs, so if your
TypedValue happens to live inside an HphpArray you can apparently
break HphpArray invariants.

Since we still often cast TypedValues to Variants when they live in
HphpArrays, using TypedValue::operator= inside of Variant needs to be
forbidden.  It also is dubious (probably wrong) in any tv_helpers
functions that mutate externally-owned TypedValues.  This particular
function turns out to be dead code anyway.
2013-07-01 13:40:55 -07:00
Sean Cannella c22db0b4be more macosx warnings
- more warnings from macosx OSS
2013-07-01 13:40:55 -07:00
Sara Golemon 252dfe987c Update folly 2013-07-01 13:40:50 -07:00
Herman Venter 4506f32342 Debugging functions in systemlib.php
After a run command, breakpoints in systemlib did not fire because systemlib.php does not get reloaded. Now get the run command to reapply the breakpoints. Also fixed the caching of the source of systemlib.php to not check for the debugger flag before the flag has been set. Finally, fixed a race condition where compiling a string/file to a unit will fail to update the repo with the unit because another thread has already written a unit with the same hash to the repo. In such cases, the losing unit is unable to retrieve source information because that only lives in the repo.
2013-06-28 11:36:10 -07:00
Herman Venter bca91c8ef3 Really turn off tutorial output this time and re-enable tests that failed because of tutorial mode.
It turns out that Tutorial=0 means "auto" and -1 means "off". With auto tutorials, the hphpd.hdf file got updated and test behavior got flaky. Even worse, the non ASCII characters in the tutorial output broke the test runner in a way that made it look like tests passed when you put up a differential, only to fail in contbuild.
2013-06-28 11:36:10 -07:00
mwilliams bc52150751 Fix encoding of default arguments
Default arguments with escape characters in were being
over escaped. The old idl.php would first eval'd the string, then
serialized the result. The new idl.cpp just serializes the original.

We have to unencode it, then serialize.
2013-06-28 11:36:09 -07:00
Todd Nowacki 6d8999b7c1 Simple HPHP Changes for HPHP with Clang
Some simple changes for HPHP to help make it clang friendly

---hphp/compiler/package.cpp
---hphp/compiler/package.h
---hphp/runtime/ext/ext_curl.cpp
---hphp/runtime/ext/pdo_mysql.cpp
---hphp/tools/tc-print/offline-x86-code.h
---hphp/util/async_func.cpp
---hphp/util/async_func.h
---hphp/util/compression.cpp
---hphp/util/compression.h
---hphp/util/db_conn.cpp
---hphp/util/db_conn.h
  Deleted unused private fields

~~~hphp/compiler/analysis/symbol_table.h
  Static assert had to be outside the union

+++hphp/runtime/TARGETS
  Added clang specific flag to supress unneded declaration warning

~~~hphp/runtime/base/datatype.h
  Use of logical '&&' with constant operand. Added !=0 to remove warning,

~~~hphp/runtime/base/string_data.h
  Static fields cannot be declared in an anonymous struct/union

~~~hphp/runtime/ext/bcmath/TARGETS
  Moved gcc specific flag from preprocessor_flags to compiler_specific_flags

~---hphp/runtime/ext/pdo_mysql.cpp
  Removed unnecessary self asignment for row_count

~~~hphp/runtime/vm/bytecode.h
  Added default return statement

~---hphp/runtime/vm/jit/codegen.cpp
  spillSlotsToSize was unused

~~~hphp/runtime/vm/jit/irtranslator.cpp
~~~hphp/runtime/vm/jit/linearscan.cpp
  The c++ standard states default arguments shall not be specified in the
  parameter-declaration-clause of a lambda-declarator.

~~~hphp/runtime/vm/jit/vectortranslator-internal.h
  Clang had some issues determining the correct cast when these macros were used
  A simple '!= 0' check was added to make things explicit for clang.

~~~hphp/tools/tc-print/perf-events.h
  Added parens to make clang happy

+++hphp/util/asm-x64.h
  The constexpr needed to be initialized

+++hphp/util/base.h
  Clang also supports tr1 libraries

~~~hphp/util/bits.h
  Again, clang had issues with implicit casting to bool.
  added != 0 check

~~~hphp/util/malloc_size_class.h
  Ambiguous operator precedence. Added parentheses.

~~~hphp/util/thread_local.h
  Misspelled function
2013-06-28 10:33:52 -07:00
bsimmers b7d178e674 Eliminate Marker instructions
This diff removes the Marker opcode, replacing it with a BCMarker
struct in each IRInstruction. This gives us fewer redundant lines in IRTrace
dumps and allows for more straightforward control of which IRInstructions are
associated with which bytecodes. I took this opportunity to do some more
cleanup of ir dumps as well, and it's now possible to interpOne every codegen
punt.
2013-06-28 10:33:51 -07:00
mwilliams 8f421ab193 Mark registers dirty before entering catch-traces
Otherwise we end up with bizarre stack corruption.
2013-06-28 10:33:51 -07:00
Eric Caruso 9a76c1ebe9 Move type dispatch of ConvCellToInt to simplifier
Currently, CastInt does this all in its HHBC -> HHIR
translation, but this could be improved.
2013-06-28 10:33:50 -07:00
Mirek Klimos eddef7ffc0 Replacing PackCont and ContExit opcodes with ContSuspend.
PackCont opcode is always followed by ContExit so let's join them into ContSuspend. ContResume counterpart may come later (replacing ContNext/Send/Raise/Enter).
2013-06-28 10:33:50 -07:00
Mike Magruder 44ae3c3dac Disable tests which are giving us grief with control chars in their output.
We've got some tests that are giving us control chars in their output on contbuild machines. We haven't been able to repo locally yet. Disabling them for now until the test harness can be improved to avoid crashing in these cases.

Note: this diff will likely go thru multiple iterations as more are uncovered.
2013-06-27 17:36:45 -07:00
Vaishaal Shankar 6f3dfaa4a3 zend comparison mismatch
Changed parts of tv_comparisons so certain comparisons to resource type matches zend
2013-06-27 17:36:43 -07:00
Sara Golemon e76acef302 Restore network newlines to mailparse test files
Match PHP's test-case format
2013-06-27 17:06:58 -07:00
Jordan DeLong 67bf707768 Fixes and improvements for type aliases
Replace NameDef with a new struct of runtime-resolved typedef
information.  This needs to include more than Class* or Typedef*,
because we might have nullable type aliases, or a non-nullable alias
to a nullable typedef, or vice versa.  Switch to the new
TypeAnnotation stuff in TypedefStatement instead of just strings so
support for this isn't weird (shapes are outside of this for now
though---see the hack in parser.cpp).  Also fixes support for type
aliases to mixed.
2013-06-27 15:14:22 -07:00
Sean Cannella 9849079ee4 fix print flag mismatch build warning on other platforms
- fix mismatch between %lu and uint64_t in printf flags
2013-06-27 15:14:17 -07:00
Edwin Smith 685fe164ae Rewrite get using nvGet()
Profile data shows much heavier use of ArrayData::nvGet(),
nvGetCell(), and exists(), than get().  So rewrite get()
using nvGet().
2013-06-27 13:00:47 -07:00
Herman Venter d074fbef0a Disable tests that fail on contbuild
These tests now seem to fail deterministically on contbuild. Disable them until we figure out why.
2013-06-27 13:00:46 -07:00
Sean Cannella 22c5361a24 redis fixes from github comments
- applying github comment fixes (thanks @staabm )
2013-06-27 13:00:37 -07:00
mwilliams 2c1919505f Allow hhas files to set the MayUseVV flag
If the last parameter is '...', set the MayUseVV flag
2013-06-27 12:59:28 -07:00
Sean Cannella 9dfaa87b44 other platform warning in codegen
- fix noisy compiler warning
2013-06-27 12:59:28 -07:00
Sean Cannella 9aaf5ab743 s_counter should still be defined on non-Linux
- s_counter still needs to be defined somewhere in
NO_HARDWARE_COUNTERS builds
2013-06-27 12:59:14 -07:00
Sara Golemon 7aa06852e4 Copy hhas string rather than attach in HHAS parse_long_string()
buffer falls out of scope and becomes invalid on return.
Copy the string so that it's still usable later on.
2013-06-27 12:12:34 -07:00
Mike Magruder db502d7451 Cleanup 'zend' command a bit
The [z]end command in hphpd runs the last manually entered snippet of php in "zend". If you typed 'z' before actually entering any php, it would segfault. Fixed a minor bug in Process::Exec, and present help if none entered. Also clarified that it will simply use your system's default php, and made it so you can override which exe to use with a hphpd config variable. The default is "php", since that is most commonly used.
2013-06-27 10:50:24 -07:00
Sean Cannella b1cc655364 fix very noisy compile warning on other platforms
- fix compile warning generating a ton of spew
2013-06-27 10:50:23 -07:00
bsimmers 4375db0f05 Fix and reenable test/quick/setprofile_throw.php
Fix a cast from a previous diff, and fix surprise checks that throw
exceptions. I turned the two macros into functions to clean things up; the
important part of the fix is taking out the SYNC() before
EventHook::CheckSurprise(). Before this fix, the saved offset in the ActRec
used for reentry would point at the offset immediate of the Jmp instead of the
Jmp itself.
2013-06-27 10:50:23 -07:00
Jordan DeLong aac60ddb1e Don't tell phabricator about skipped tests in test/run 2013-06-27 10:50:22 -07:00
mwilliams 0632fb3a11 Allow .hhas to specify default values
It only matters for reflection, but hhas parameters with
default values need to specify the text of the string.

In addition, change reflection to report parameters with no
default value string as not having a default value, to avoid
crashing when trying to access it.

Update the "func" parameter of array_filter to have a valid
default. The other uses of defaults in array_map and array_filter
are just to get the proper behavior on too few/too many args,
and don't really correspond to default values.
2013-06-27 10:50:22 -07:00
Mike Magruder 6bf4fb404e Fix flow_gen.php to track https://phabricator.fb.com/D864123
A recent diff broke this test. Fixing it up... the issue was that a codegen change altered the number of instructions in Continuation::send().
2013-06-27 10:50:22 -07:00
Jordan DeLong f828a7af6d Never allow typedefs with the same names as classes
Right now, we allowed it as long as the typedef was for the
same class.  (Oversight.)  This involved a few error message changes
in existing tests.
2013-06-27 10:50:13 -07:00
Sara Golemon c4550d2b24 Fix license header in asio 2013-06-27 10:50:12 -07:00
Jordan DeLong 62dd2e2aae Allow type constraints on opaque type aliases
Allows some syntax that is ignored at runtime; only used
ahead of time by the type checker.
2013-06-27 10:50:12 -07:00
Edwin Smith 89ffdb7a01 Remove uses of BOOST_STATIC_ASSERT
Ow, my eyes!  use static_assert instead.
2013-06-27 10:50:11 -07:00
Jordan DeLong 69768a0836 Remove some unused or mostly unused Variant typedefs 2013-06-27 10:50:02 -07:00
Jordan DeLong 90e73bdf6c Add a cellIsPlausible assertion
Cleans up a few assertions in tv_comparisons and I want to
use it elsewhere.
2013-06-27 10:50:01 -07:00
Herman Venter e9fcf01b3d Encode test ouput before returning it to the test framework
When a test fails hphp/test/run runs a regular expression over the test output and returns it to the python scripts that is running the tests on the continuous build machine. These scripts crash if presented with output that is not printable ASCII, which makes it very difficult to figure out why the test is failing. This change modifies hphp/test/run to first encode the test output with quoted_printable_encode before returning it to the python scripts.
2013-06-27 10:50:01 -07:00
Jan Oravec f0dcca8b29 Kill m_received, transfer values thru stack
Continuation's m_received field is used to transfer values and
exceptions to the Continuation by send() and raise() methods. It has a
valid value only for a short duration of time, between
ContNext/ContSend/ContRaise and UnpackCont opcodes, when no other
operations could possibly occur. Let's free these 16 bytes of memory and
pass the value thru the VM stack.

To achieve this goal, ContEnter was modified to accept a value to be
transferred on the stack. The existence of the value on the stack is
then acknowledged by the UnpackCont opcode, which is the first opcode
executed after ContEnter enters the continuation body.

ContNext then becomes a trivial Null and is thus removed, ContSend just
teleports the value from local 0 to the stack (I will experiment in a
follow up diff with replacing ContSent by CGetL+UnsetL). ContRaise has
to update the label, but the eventual plan is to enter into unwinder
directly from the raise() method.
2013-06-27 10:50:00 -07:00
Jan Oravec 5b9e01ff47 Do not hold unnecessary reference to sent value
Continuaton::send()/raise() are holding reference to the sent value
while the next iteration is being executed. Do not hold this reference
and teleport values instead.
2013-06-27 10:50:00 -07:00
Sean Cannella 04fc9c6993 fix type declaration build warning on other platforms
- fix type declaration mismatch (long vs. int64_t) on other platforms
2013-06-27 10:50:00 -07:00
Sean Cannella 0a80f93ea4 __assert_util is not defined on macosx
- use the HHVM assert_util implementation on OSX
2013-06-27 10:49:59 -07:00
Sean Cannella 779904e538 fix potentially uninitialized warning on other platforms
- fixes compiler warning about variable that might not be initialized on other platforms
2013-06-27 10:49:59 -07:00
Sean Cannella 84672b7782 fix type mismatch in asio declaration
- Fix declaration of type mismatch that shows up on other platforms
- Fix lint warnings re: 80 characters
2013-06-27 10:49:59 -07:00
Jan Oravec 2a1d59c286 Move Continuation state check to ContCheck opcode
Add ContCheck opcode that moves away responsibility of checking
Continuation status from Cont{Next,Send,Raise} opcodes.

This check needs to run outside of try/catch in next()/send()/raise()
methods and moving it to a separate opcode lets us merge
Cont{Next,Send,Raise} with ContEnter.
2013-06-27 10:49:58 -07:00
Joel Marcey fc4ed71839 Fix PDO MySQL bug in getColumnMeta()
In trying to get the CakePHP Blog Tutorial to run on HHVM, a subtle bug was found where the table name was not being returned, and, instead, an numeric index was being used. The bug was in PDOMySqlStatement::getColumnMeta (pdo_mysql.cpp). Applying this fix, the flock/fwrite fix (D855470) and the Reflection::SetAccessible (D851647) fix makes the CakePHP tutorial run like a champ.
2013-06-27 10:48:32 -07:00
Mirek Klimos 5d09e8a87c CreateCont opcode cleanup - removing FillContLocals instruction
FillContLocals was used only when num of locals > kMaxInlineContLocals; it doesn't hurt performance to copy them always within hhir.
2013-06-27 10:45:56 -07:00
Sara Golemon a3f507d58d Add reference to extension object to class_map
Add IDL component:
{
  "extension": {
    "symbol": "s_foo_extension"
  }
}

extension.symbol is the C++ HPHP::Extension symbol for the
extension (if one exists and is exported).
2013-06-27 10:45:56 -07:00
Bert Maher bb7dff89d9 Make unit.cpp not take forever to compile
The AtomicHashMap constructor seems to be causing
Unit::GetNamedEntity to take forever to compile in the opt build, so I
moved the initialization out of that function and marked it #pragma
GCC optimize ("O0") to prevent whatever crazy optimization is freaking
gcc out.
2013-06-27 10:39:17 -07:00
mwilliams 07dde58004 Remove a not-yet-true assert
In some circumstances we create unreachable blocks,
making the assert invalid. Currently nothing depends on the
assert being true, so remove it for now.
2013-06-27 10:39:16 -07:00
Edwin Smith ada27dfc01 Use KindOfInvalid instead of KindOfTombstone
KindOfInvalid is -1, so IS_REFCOUNTED_TYPE() == false, which
will allow skipping a few tombstone checks in future array work.
But also, it avoids declaring a magic constant outside the
DataType enum, and sometimes gcc can generate better code for
comparisons with 0 (ie type<0) than it can for 0x62, the value
of KindOfTombstone.
2013-06-27 10:38:23 -07:00
Herman Venter 2bf7800c0d Replicate debugger stack tests in test/quick/debugger
Ongoing migration of tests to the new infrastructure. The old tests stay in place until we have another way to test the client API.
2013-06-27 10:38:23 -07:00
Bert Maher 43d2ed7c7c Add PHP function mapping to stacktrace profiler
Adds translation of addresses to PHP function names using the
map created for perf.
2013-06-27 10:38:23 -07:00
Herman Venter 7b75527b3d Replicate debugger info tests in test/quick/debugger
Ongoing migration of tests to the new infrastructure. The old tests stay in place until we have another way to test the client API.
2013-06-27 10:38:22 -07:00
Mike Magruder 96c7a1ce81 I can haz moar usage logging?
Add a bit more usage logging for the debugger, and ensure that there is a common field between clients and servers thats easy to search on, i.e., sandbox id.
2013-06-27 10:38:22 -07:00
bsimmers 26c74bf8e9 Pass known Func*s through in the region translator
Pretty straightforward, since the hard part of figuring out
when the Func* is known is still handled in Translator::analyze.
2013-06-27 10:38:22 -07:00
bsimmers f928f1b320 Support interpOne in translateRegion
This was going to be easy, but then it wasn't. The existing
interpOne relied heavily on the outputs of NormalizedInstruction, and
those are only populated by code that we want to kill soon. It also
didn't properly deal with bytecodes that wrote to more than one local,
or more than one stack cell. So the bulk of this diff is rewriting
interpOne to not rely on the NI outputs, then it was simple to hook it
into the region translator. I also cleaned things up so we don't
attempt to translate instructions that have no hope of succeeding; we
just interp them on the first try now.
2013-06-27 10:38:22 -07:00
bsimmers d99c6b0c58 Handle parameter reffiness in translateRegion
This diff stops the region translator from punting on
instructions that may be prepped by ref (FPass*) or Tracelets with
reffiness guards. It increased coverage and exposed a few more
bugs. The only significant one was that some Tracelets depend on type
prediction for their length, so I had to hook it into translateRegion
to avoid generating worse code (or punting).
2013-06-27 10:38:21 -07:00
Jan Oravec 514838183c Kill linking of variable environments
Apparently VarEnv's m_previous is not used for anything. Let's kill its
maintenance and avoid 2 native calls per Continuation
next()/send()/raise() calls.
2013-06-27 10:38:21 -07:00
Sara Golemon 2811e9da94 Implement Redis extension
PHP implementation of Redis
2013-06-25 13:19:10 -07:00
Herman Venter a372e0063c Re-enable debugger tests that were suspected of flakiness
These tests failed on the continuous build server, so we disabled them. Since then many other tests have failed and there is no good reason to suspect these tests of being especially flaky, so we may as well re-enable these tests.
2013-06-25 13:19:10 -07:00
Eric Caruso 4a86eb9f1f Implement EmptyIterator, InfiniteIterator, NoRewindIterator
This makes 14 zend tests happy. It also requires some
real stupidity, but PHP iterators are weird.
2013-06-25 13:19:09 -07:00
bsimmers 683bb8af52 Fix hhvm tests
I messed up rebasing my Op enum class diff
2013-06-25 13:19:09 -07:00
Sara Golemon 70dac3df33 Support .skipif in test/run
Calls the first .skipif file to be found of:
$testname.skipif
./config.skipif
../config.skipif
../../config.skipif
etc...

And skips the test if that PHP file outputs anything.

Also expands $test.opts, $test.hdf, and $test.in to
look in config.* and parents
2013-06-25 13:19:08 -07:00
bsimmers 6d91f8195a Turn HPHP::Op into an enum class
Because stronger types are better types, and this will make
future refactoring easier. I considered trying to purge the Opcode
type from the codebase too but that would be a much bigger project.
2013-06-25 13:19:08 -07:00
Jordan DeLong 6b891c8331 Support checking option type typehints at runtime.
Adds support for checking ?Foo type hints in VerifyParamType.
The parameter must have type Foo or null.  Failing to pass the hint is
reported as a warning instead of a recoverable error for now for
migration reasons---we'll want to convert it to be the same as normal
type hints later.
2013-06-25 13:19:08 -07:00
Jordan DeLong afc51da4c6 Move bytecode.cpp use of comparisons to tv_comparisons functions
Instead of calling into the comparisons.h stuff, call into
the cell/tv functions.  This meant moving more_or_equal and
less_or_equal to tv_comparisons and moving cellToBool out of its
unnamed namespace.  Also replaces the global tv() function with some
make_tv() and make_value() thing---it looked like it was incorrect for
doubles, and since the correct compile-time type for the unconstrained
template parameter essentially depended on the runtime value of the
first parameter it seemed more reasonable to move that to
compile-time, too.
2013-06-25 13:19:07 -07:00
Jordan DeLong f3d2185982 Delete Variant's implicit conversion operators 2013-06-25 13:19:07 -07:00
Sean Cannella 3d0c614b9a convert enums to enum classes, part 3
C++11 cleanup (clean up easy enums)

This is for runtime/base/... and ended up touching a lot of files
because it turns out we have a lot of reasonably behaved enums.
2013-06-25 13:19:06 -07:00
Jordan DeLong 4d5f36126d Remove equalAsStr (perflab can't detect the optimization)
There is only a single call-site for all of this thing.  I
figured perflab could be the judge on whether to reimplement the usage
in a more reasonable way, or just delete it---looks like option 2 is
good.
2013-06-25 13:19:06 -07:00
Owen Yamauchi dfd9746561 Get rid of NameValueTableWrapper, part 1 of 3
It was used to indirect from an array to a Class's propVec during
86pinit methods, but this isn't a significant technical obstacle.
We now just pass in a regular HphpArray and pull values out of it after
invoking the method.

Part 2 will do the same for 86sinit methods (it's a slightly more
involved change, and I want to keep it maximally broken down for
revertibility). Part 3 will delete NVTW itself.
2013-06-25 13:19:05 -07:00
mwilliams 8ea5b023a8 Fix EnableRenameFunction for tests
The slow tests were supposed to run without it, except when they
explicitly requested it, but test/run always set it on the command line.

This moves it into the default config.hdf, and removes a few cases where
it was explicitly turned off in the slow tests.
2013-06-25 13:19:05 -07:00
Sean Cannella 303ea58976 convert enums to enum classes, part 2
C++11 cleanup (clean up easy enums)

Since sandcastle is failing:
2013-06-25 13:19:05 -07:00
Sean Cannella 4872a71b36 convert enums to enum classes, part 1
C++11 cleanup (clean up easy enums)

Since sandcastle is failing:
2013-06-25 13:19:04 -07:00
Paul Tarjan 506f21c4b5 Allow extension functions to match zend calling convention
Introducing `ZendParamMode` to as a idl flag. We are not consistent with zend on how they do their params for builtins. We cast to the expected data type. They do some checks, and if the checks don't pass they issue a warning and return (usually) `null`. This diff starts us down that path.

I'm introducing the param and using it in the places where we were emulating the calling convention in the `f_foo` functions. I'm going to follow up with converting as many as I can and then eventually this becomes the default. I also want this to be applied to php files in systemlib.

Many of the conversions are from https://github.com/php/php-src/blob/master/Zend/zend_API.c#L305
2013-06-25 13:19:04 -07:00
Sara Golemon fd94725e57 Get rid of runtime/base/hphp.h
This is a vestigal limb of HPHPc
which caused global_variables.cpp to way over-include
by way of runtime/ext/ext.h
2013-06-25 13:19:03 -07:00
Todd Nowacki adda9a5022 HPHP Changes for Clang
More changes for HPHP to help make it clang friendly

~~~hphp/compiler/expression/constant_expression.h
~~~hphp/compiler/expression/function_call.h
  rfind returns a size_t/unsigned int

~~~hphp/runtime/base/server/http_protocol.cpp
  Switched to std::to_string. Assuming [] was not intended here

~~~hphp/runtime/base/ref_data.h
  These fields were accessed in a public manner, assuming public was intended
  instead of private

~~~hphp/runtime/base/variable_serializer.cpp
  Switched to using [] and & to make clang happy. Assuming this was to either
  take or drop the first char.

~~~hphp/runtime/ext/asio/asio_external_thread_event_queue.h
~~~hphp/runtime/ext/asio/asio_external_thread_event_queue.cpp
  Cast  which performs the conversions of a reinterpret_cast is not
  allowed in a constant expression. This is been moved to a macro as a temporary
  fix.

+++hphp/runtime/ext/ext_misc.cpp
  Added std::atomic to supress warnings

~~~hphp/runtime/vm/jit/simplifier.cpp
  Chosen constructor is explicit in copy-initialization

~~~hphp/runtime/vm/jit/translator-asm-helpers.S
  Ambiguous instructions require an explicit suffix
  Changed cmp to cmpl

~~~hphp/runtime/vm/jit/translator-x64-helpers.cpp
  Clang does not support global register variables

+++hphp/runtime/vm/unwind.cpp
  describeFault was only used when DEBUG or USE_TRACE was defined

~~~hphp/runtime/vm/verifier/check_unit.cpp
  Made fmt pointer const to avoid string format issues/warnings

~~~hphp/util/stack_trace.cpp
  Clang does not support variable-length arrays.
  Uniqe_ptr is used instead to take advantage runtime-sized arrays, a
  restriced form of variable-length arrays

~~~hphp/util/thread_local.h
  Clang seems to be supporting the __thread attribute, or at the very least
  it is not complaining about it.

~~~hphp/util/tiny_vector.h
  Clang does not like the flexible array here, since T is not always POD.
  I have reimplemented the array here by just sticking one value in the struct
  and calculating the offset from its address manually.
  Alterinatively, we could change the the non-POD types to be pointers, or
  we could edit their implemenations.

+++hphp/util/util.h
  Created a template for the union,
  A function declared with the constexpr specifier cannot contain
  type declarations that do not define classes or enumerations

+++hphp/runtime/vm/jit/x64-util.h
  Added a TODO
  The way hphp/runtime/vm/jit/x64-util.h is currently implemented, it only
  works if USE_GCC_FAST_TLS is defined
2013-06-25 13:19:03 -07:00
Eric Caruso 533ed5d493 Implement LimitIterator
Implements LimitIterator from SPL.

Closes #788
2013-06-25 13:19:03 -07:00
Paul Tarjan f2b3611f48 increase timeout
scrypt is taking too long, and I think the other tests are having some trouble
2013-06-25 13:19:02 -07:00
Jordan DeLong f56d1fed4e Try not to look up scalar class constants in targetcache
Instead, just check the class is defined and is the class we
expected at translation time (side exiting if not), and just use the
scalar value directly.  If the class is Persistent or a parent of the
current context we don't need to check the Class* either.
2013-06-25 13:19:02 -07:00
Jordan DeLong 21dfaaf50e Various small optimizations for JIT compile time perf @override-unit-failures
While debugging a flib test that times out due to bad
compile-time behavior, I fixed several small sources of bad perf
before giving up on trying to just make things fast enough.  Most of
these came from profiling while the flib test repeatedly compiled a
tracelet with close to 100k SSATmps (it keeps side-exiting and
recompiling).

Details:

  - Waiting until codegen for punting on DefCns made some tracelets
    take really long to compile (when they just consist of a bunch of
    DefCnses).

  - In LinearScan::collectInfo, m_jmps.reset() was the top of the
    profiler (since we do it for each exit trace), and from talking
    with @swtaarrs it seems like it can be just omitted.

  - dce.cpp consumeIncRef was trying to memoize in a way that involved
    creating hphp_hash_sets for each SSATmp; removed that.  (Someone
    should double-check I didn't break the algorithm if possible
    because I didn't quite spend the time to 100% understand it.)

  - dce creates a new StateVector<SSATmp,SSATmp*> for each exit trace
    when sinking.  Since the tracelet in question had a side exit for
    about 1/3rd of the HHBC ops, this was kinda bad.  It's also pretty
    sparse, so I just changed it to a smart::flat_map.

  - Convert WorkList from std::list to smart::list.  (Should maybe be
    smart::deque but I didn't want to test fixing the remove() call.)
2013-06-25 13:19:01 -07:00
Jordan DeLong 60036dcdbf Add smart::flat_map and smart::flat_multimap 2013-06-25 13:19:01 -07:00
Paul Tarjan cf37a18981 Use previous version of script
i accidentally committed the wrong version of the diff
2013-06-25 13:19:01 -07:00
Paul Tarjan 5d695acedb Update timelib and datetime functons to match 2013-06-25 13:18:25 -07:00
Paul Tarjan d0f3c0b8ab use timeout in php
Use a script from http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3
2013-06-25 12:22:59 -07:00
bill fumerola 2096cd0acc GenMapWaitHandle - a BlockableWaitHandle that wait for a Map of WaitHandles
add GenMapWaitHandle, a compliment to GenVectorWaitHandle and GenArrayWaitHandle.
2013-06-25 12:22:59 -07:00
Mike Magruder 6e6ebfe8d8 Change hphpd –h option to make it a little easier to use, provide warning when no server specified
People sometimes make mistakes and launch hphpd without connecting to a server, but expect to be in the server environment when evaluating expressions. Modified the –h option to not require a host specification, and default to localhost, so "hphpd –h" is a valid way to launch now. Provide a warning on launch when no args are specified at all warning the user that they're not connected, and giving suggestions for how to connect if necessary. There are reasonable use cases for launching hphpd with no args (so, no connection and no local script to debug) and I didn't want to take those away by automatically connecting to a server at localhost if launched with no args. I'm hoping the warning is sufficiently helpful.
2013-06-25 12:22:59 -07:00
mwilliams 090ca545ff Fix shutdown crashes in xbox/pagelet server
Various code tested to see if xbox was enabled by the
config, but what it really cared about was whether there was
an xbox dispatcher. During shutdown we stop the XboxServer before
the main server, so there's a short window where the XboxServer
is enabled by the config, but there is no dispatcher. If a running
thread tries to run xbox code, it would crash.

Switch the tests to test s_dispatcher and hold a lock, rather than
testing the config.

Fix similar issues with PageletServer, (although we don't currently
shut it down until process exit - I'll post a follow up diff to fix that).
2013-06-25 12:22:58 -07:00
Edwin Smith 8317e1e59e Ensure all static strings come from the same table.
GetStaticString() is now the only way to get a static string,
so enforce it and short-circuit out when asking for an already-
static string.

Add a GetStaticString(data,len) overload and up some dead code along the way.
2013-06-25 12:22:58 -07:00
Dario Russi c9daa2175f Foreach phase1: expose collection types to foreach JIT helper
Create a set of templatized functions for iterator over collection and bubbled them up closer to the JIT entry point for foreach.
2013-06-25 12:22:58 -07:00
Jordan DeLong 7a08c6e6fa Don't put non-Unique classes into the instanceof bitmask @override-unit-failures
We want to throw exceptions if someone does "instanceof Foo",
where Foo is a type alias.  The easiest way to make sure the
instanceof bitmask optimization doesn't get in the way of this is to
not allow it on non-unique classes, assuming this is ok perf-wise.
2013-06-25 12:22:57 -07:00
Jordan DeLong 7d99716399 Beef up type alias mixedcase unit test
Add a few more cases that weren't tested.
2013-06-25 12:22:57 -07:00
Jordan DeLong e08d0ca2b1 Delete a couple functions in ArrayData
If you are dealing with const StringData*'s, they convert to
bools and call CVarRef overloads here.  (I'm sure there's others, and
this conversion for CVarRef should go away soon, but we might as well
have this for now to possibly catch bugs ahead of time.)
2013-06-25 12:22:56 -07:00
Jordan DeLong 1c710536b1 Mark classes with the same name as a type alias as redeclaring @override-unit-failures
If you have an alias named "Foo", and a class named "Foo" in
the same program, we should not be treating instanceof (and probably
other things) as if the class name is unique.
2013-06-25 12:22:56 -07:00
mwilliams fdc153980f Fix typecheck crashes
We didn't fill in the m_namedEntity field for hiphop-only type
hints in non-hiphop mode, resulting in crashes when we tried to
use them.

Regardless of mode, we didn't check self or parent before
checking a non-object parameter, resulting in asserts in
dbg builds and seg-faults int opt builds.
2013-06-25 12:22:56 -07:00
Paul Tarjan cdffeebb97 I was using a binary with the new timelib. Undo the datetime tests
Test Plan: ran zend tests
2013-06-25 12:22:55 -07:00
Paul Tarjan 5d998b32c0 zend test upgrades
* change warnings from `%a` to `%s`. This way, we don't eroneously match more than one line for an error message
* import all the 5.5 tests since it is now official

I checked through all the tests that went from good to bad, and each one is correctly failing. Most of them are from us doing the extension calling-convention wrong.

The only thing to review is the change to `tools/import_zend_test.py`
2013-06-25 12:22:54 -07:00
Paul Tarjan 57c3d0250b remove extra tempname
This fixes the test in travis
2013-06-25 12:22:53 -07:00
Paul Tarjan a75ac9b498 remove duplciated content
I think you double imported this. It is all in `lwp.php`
2013-06-25 12:22:53 -07:00
Paul Tarjan 0b02291c12 make test less specific
some machines say `localhost.localdomain`. Think this is good enough?
2013-06-25 12:22:53 -07:00
Paul Tarjan 63fc74a751 reflection for namespaced constants
In repo mode this does the right thing and returns the right constant, but for non-repo it thinks it is an undefined non-namespace constant. I'll have to do something more hardcore if that starts to matter

While I was in there, I made the correct name for `ReflectionParameter` that was added in 5.4 instead of the draft we copied.
2013-06-25 12:22:52 -07:00
Jordan DeLong 1df58ddcbf Don't set $env 2013-06-25 12:22:52 -07:00
Jordan DeLong 1aa7ad7819 Modify lwp tests that try to run php in a subprocess
Open source continuous integration doesn't have php available
to run.
2013-06-25 12:22:52 -07:00
Mirek Klimos 56ddbc6bd3 CreateCont opcode optimization - avoid unnecessary reference counting.
Continuation argument values are copied to the continuation object and the locals are unset - in this way we don't need to change the reference coutners.
2013-06-25 12:22:51 -07:00
Eric Caruso 463290b8ea Adds decl and decw instructions that operate on registers
Cherry-pick of D851076 which was reverted in the OSS
segfault catastrophe.
2013-06-25 12:22:51 -07:00
Herman Venter 524ada08bc Tolerate output spew generated by the readline library on some machines
It seems that on some machine configurations the readline library has the bad idea of spewing some control characters to stdout. This causes failures in any test that is reading from the command line, which currently only happens in debugger tests. Possibly this behavior shows up on the continuous build machines, so we'll make the expected output provide for this variation, just in case.
2013-06-25 12:22:51 -07:00
Paul Tarjan d3e6ade96f fix all the $_SERVER urls - take 2
I needed to `m_origPathInfo.reset()` in `RequestURI::clear`
2013-06-25 11:42:33 -07:00
Paul Tarjan b9058d036e add SessionHandler
In PHP 5.4 they added this class that encased the callback functions. The difficulty came with needing to fallback to the previously registered session handler.

Closes #792
2013-06-25 11:42:33 -07:00
Paul Tarjan 23c8e35811 make sysdoc.php not write WarningThis
Also, while I was in there I made the script not spew anything on the terminal.

@markw65 `array_filter` doesn't match the signature from php.net. Should it?
2013-06-25 11:42:32 -07:00
Mike Magruder b7d2212723 Remove useless interpreting flag from execution context
We were maintaining a flag that said if we were interpreting on the EC. It was only used in the implementation of hphp_break(), for pretty minimal benefit. I yanked it… it seems fine to me to throw the switch exception if someone steps out of the hard break even if we're already interpreting.

Also yank out a vestige of the previous stepping and breakpoint logic from the dispatch loop I noticed today. I'd previously missed it, but I made a change a while ago to put the state of the last location filter into the hands of the flow control commands. This was unnecessary and should have been removed then.
2013-06-21 16:37:12 -07:00
Paul Tarjan 3cbf137805 small fixes to SplFixedArray
`is_numeric` is a superset of `is_int` and 2 of these tests don't pass until we get Zend calling convention over stdlib.
2013-06-21 16:37:12 -07:00
Dario Russi a94e453dd6 Complete work for CGetM, SetM, FPassM and IssetM applied to collections
Added helper for the remaining collection types, emit guards and call specialized helper for the above opcodes
2013-06-21 16:37:11 -07:00
Eric Caruso 035b3eaff7 Adds word-size instructions to x64 assembler
Retry of D848605 which doesn't segfault the open-source build.
Formerly, this change caused the assembler to emit an opsize
prefix before ret instructions taking a 16-bit immediate, which
worked on our machines but caused problems for Travis CI.
2013-06-21 16:37:11 -07:00
Herman Venter 1197521469 disable flaky test
Fails on continuous build server
2013-06-21 16:37:11 -07:00
mwilliams 9cecd8956a Shut down pagelet server before exiting
There was nothing stopping a pagelet thread from continuing
to run after the server was shut down. If it continued to run after
main exited, it could access data structures (such as the global maps
used by Apc and FileRepository) that had been torn down, and crash.
2013-06-21 16:37:10 -07:00
mwilliams 000eadc430 Read the last commands from a light process
poll can set both POLLIN and POLLHUP. We were checking for
POLLHUP first, which meant we often missed the "exit" command. This
meant the LightProcess would incorrectly report that it was exiting
because it lost its parent, rather than because it was told to exit.

Fixing this so its easier to diagnose what was going on.
2013-06-21 16:37:10 -07:00
Sean Cannella 51ce8d138a remove tx64 dependencies from runtime/vm
Refactor platform-independent/interface methods into translator
so runtime doesn't depend on tx64 directly
2013-06-21 16:37:10 -07:00
mwilliams 679fb61d40 Clear g_procs before closing light processes
Otherwise, the SIGCHLD handler will trigger a server shutdown.
The only time this is bad is when LightProcess::Close is called
from the segfault handler, because it triggers a server shutdown
while we're dealing with the initial crash, which almost always
leads to misleading core dumps.
2013-06-21 16:37:10 -07:00
mwilliams 26396ca0e1 Throw an exception, not a pointer to one
It will probably work better.
2013-06-21 16:37:09 -07:00
bsimmers 8f6c65a550 Add an option to test/run to pass through extra runtime options
This is useful when testing out a new feature that's hidden
behind a runtime option.
2013-06-21 16:37:09 -07:00
Herman Venter b66f8587e8 Disable flaky tests
test/quick/debugger/break1.php and test/quick/debugger/break2.php are failing on the the continuous build machines. Disable these tests while we figure out what is going on.
2013-06-21 16:37:09 -07:00
Mike Magruder e3f34ac774 Don't warn when there is no debugger startup doc
It's perfectly valid to have no debugger startup doc configured for a server. The code was a bit silly in that case.
2013-06-21 11:45:54 -07:00
Herman Venter 52804d5874 Generalize breakpoint matching involving relative paths
Currently a breakpoint specified as relativefilepath:lineno will match only if the relative file path is a simple file name or if sandbox root + relative file path is an exact match. This is now generalized so that matching occurs if the relative file path is a suffix (path) of the absolute path of the execution location.
2013-06-21 11:45:54 -07:00
Sean Cannella e1b843862d runtime/base should not depend directly on tx64
remove dependencies on tx64 for runtime/base (by refactoring platform-independent code into translator)
2013-06-21 11:45:53 -07:00
Eric Caruso f3e34edab5 Match Zend behavior for openssl_pkey_get_{public,private}
We weren't treating array(key, passphrase) correctly.

Closes #815
2013-06-21 11:45:53 -07:00
Herman Venter 026be6adbd Add test case for hitting breakpoint of the form DerivedClass::inheritedMethod
It turns out that this feature already works. Adding a test case to make sure it stays that way.
2013-06-21 11:45:53 -07:00
Mike Magruder 94793b70da Add info about debugger config to our runtime options doc
This is what people need to enable debugging for their servers.
2013-06-21 11:45:53 -07:00
Mike Magruder 4b4123f935 Debugger developer documentation.
Adding some developer docs for the debugger. The idea is to give an overview of the major implementation points so we can refer to them from the source when necessary.
2013-06-21 11:45:52 -07:00
Edwin Smith 5ec269bf85 Fix up style of StaticString declarations.
At the top level of a file, "const" is the same as "static const",
and reduce the stuttering.
2013-06-21 11:45:52 -07:00
Paul Tarjan c56c17e1d1 switch to an extension that is actually used
just 'cause it is in the `facebook/extensions/` dir doesn't mean we use it. I checked this one and it is loaded internally and not open source.
sosorry
2013-06-21 11:45:52 -07:00
Jordan DeLong 3bb3b3df13 Fix ostensive bug in sorting debugger constants
This was doing ref(foo), where foo is an Array.  This will
create a temporary Variant, call the ref(CVarRef) overload, which
casts the temporary to a non-const RefResult, then a temporary
VRefParam is implicitly constructed from this, which creates a
KindOfRef and points the temporary variant at that.  The sort will
operate on this temporary (leading to copy on write, and storing the
new ArrayData* there), so the m_constants field won't reflect the
changes.
2013-06-21 11:45:51 -07:00
Jordan DeLong 811b11711b Put a lid on test_ext for now
Hopefully stops the php file from auto-generating test stubs,
and adds a comment discouraging adding more of them.  For now I'll
stop porting the remaining ones to php: the left over tests mostly
start test servers, except TestExtTao and TestExtServiceRouter.
TestExtTao is kinda big, so I'm skipping it for now, and ServiceRouter
actually tests C++ functions (although it has a lot of use of the
smart pointer API), not extension functions.
2013-06-21 11:45:51 -07:00
Jordan DeLong c65b3bda41 Port TestExtProcess to php 2013-06-21 11:44:42 -07:00
Jordan DeLong efb4b89252 Port TestExtPdo to php
Leaves out the mysql test, which was disabled.
2013-06-21 11:44:41 -07:00
Jordan DeLong edf410ad86 Port TestExtPosix to php
Dropped tests that just called functions and did no testing
of the the result (the probability they'll catch a bug is around
zero).
2013-06-21 11:44:41 -07:00
Paul Tarjan e929e800b5 fix new php tests for open source
This was a pretty bad import into open source :(

https://travis-ci.org/facebook/hiphop-php/builds/8251282

* date tests assumed PDT. I tried putting `date_default_timezone_set("America/Los_Angeles");`. Lets see if that helps.
* options test checked for `phpmcc` which is only a facebook thing
* I'm not sure what is wrong with hash or network, but their output totally masks the real value. Made the tests output their value so I can at least test in prod.
2013-06-21 11:44:41 -07:00
Andrei Alexandrescu a33a4b0b19 PolicyArray: implement NOT_IMPLEMENTED methods
This implements the "last" unimplemented methods in ArrayShell. The sorting-related methods need no implementation because PolicyArray scales to HphpArray before sorting.
2013-06-21 11:44:41 -07:00
Sean Cannella d1b3172352 remove hphp_process_abort
- Remove questionable hphp_process_abort debugging method
2013-06-21 11:44:40 -07:00
Herman Venter 8d25c0f6f2 Give feedback if breakpoints won't hit because a file is not loaded, a class is not loaded, or a function is not loaded
The debugger client now accepts feedback from the the debugger server about whether a breakpoint can be hit, absent further loads of files, classes or functions.
2013-06-21 11:44:40 -07:00
Joel Marcey 530efd6760 Add default values to parameters of SplFileObject::flock(),fwrite()
Trying to get CakePHP running on HHVM revealed warnings around SplFileObject flock() and fwrite(). E.g., HipHop Warning: flock() expects exactly 2 parameters, 1 given. Added default values for those particular parameters
2013-06-21 11:44:40 -07:00
Andrey Sukhachev e1f159ba78 Fix the Content-MD5 handling.
The current implementation is broken, as the Content-MD5 is
computed over the uncompressed response instead of the compressed one.
RFC-1864 states that only Transfer-Encoding can be applied after the MD5
is computed, not the Content-Encoding.

We don't use Content-MD5, so this bug remained latent up until now.

Also verifying that the PHP side computed the MD5 correctly.

not sure what's happening
2013-06-21 11:44:39 -07:00
Jordan DeLong 7eb65ff688 TestExtMcrypt -> php 2013-06-21 11:44:21 -07:00
Sara Golemon 3cb57c36f0 Remove errantly added includes 2013-06-21 11:39:03 -07:00
Jordan DeLong f0afa537d6 Port TestExtOpenssl to php 2013-06-21 11:38:45 -07:00
Jordan DeLong f435bf5ba7 Move TestExtSession to php 2013-06-21 11:33:24 -07:00
Jordan DeLong 3d3865c34e Port TestExtZlib to php
Also fixed the memory leak.
2013-06-21 11:33:24 -07:00
Jordan DeLong f42ce41179 TestExtOutput -> php 2013-06-21 11:28:47 -07:00
Sean Cannella 4ed3495700 remove one more dead method
remove another dead method
2013-06-21 11:26:05 -07:00
Sean Cannella 7659942d52 remove unused platform-specific references
remove unused references to platform-specific code
2013-06-21 11:26:04 -07:00
Paul Tarjan 9fbfca6510 fix typo in SplFixedArray 2013-06-21 11:26:04 -07:00
Jordan DeLong b053111f16 Retry port binds a few times in ext_stream test @override-unit-failures
The ext_socket test actually already does this.
2013-06-21 11:26:04 -07:00
Jordan DeLong 104f003257 TestExtMailparse -> php 2013-06-21 11:25:34 -07:00
mwilliams 6342bdbf1b Don't pass environment variables with "\n" to LightProcesses
A recent diff started (correctly) passing the environment
through to child processes. It turns out our LightProcess implementation
can't handle environment variables with new lines in them, so (for now)
strip out any such variables.
2013-06-21 11:21:43 -07:00
parent5446 61ec6703fc Added missing PHP SPL classes
Added PHP implementations for PHP SPL classes that are currently missing from HHVM. These include:

- SplDoublyLinkedList
- SplQueue and SplStack
- SplFixedArray
- SplHeap, SplMinHeap, and SplMaxHeap
- SplPriorityQueue
- SplTempFileObject

Closes #807
2013-06-21 11:21:43 -07:00
Jordan DeLong 6fe6e59c0e TestExtSoap -> php
Except one part that didn't work.  (Tasked.)  Also discovered
a SEGV (tasked).
2013-06-21 11:21:42 -07:00
Jordan DeLong 2147b11334 TestExtSqlite3 -> php
Except part of it that SEGVs in the JIT.  (See task.)
2013-06-21 11:21:42 -07:00
Jordan DeLong e1b03d674a TestExtVariable -> php 2013-06-21 11:21:42 -07:00
Jordan DeLong 877f06c1e1 TestExtString -> php 2013-06-21 11:21:41 -07:00
Jordan DeLong 72c4d16df2 TestExtStream -> php 2013-06-21 11:21:41 -07:00
Owen Yamauchi 35fafe5545 Run shutdown handlers before running request-exit cleanup
Shutdown handlers can run user code (e.g. the session stuff serializes
the session and can pass the serialized blob to user code to do
something with), so it's generally not safe to run them after
requestExit(). In particular, requestExit destroys global variables, and
the session serializer reads $_SESSION.

My recent diff to get rid of the hardcoded globals exposed this, though
I argue this situation was incorrect all along.
2013-06-21 11:19:34 -07:00
Paul Tarjan 07fe7cd4a0 make test runner match php style
fixed lint finally (since we didn't have lint when i authored this)
2013-06-21 11:19:34 -07:00
Paul Tarjan 3064830921 disable ext-filter/049.php
We don't serialize doubles correctly in the repo, so this test passes on first try, and fails on second try.
2013-06-21 11:19:33 -07:00
Jan Oravec 621a7d9c55 Pass generator body Func* to c_Continuation::alloc()
Pass generator body Func* to c_Continuation::alloc(), which is then
passed to the new helper that computes ActRec offset.
2013-06-21 11:19:33 -07:00
mwilliams dde3c9e8d8 Fix tvSame for null-by-reference values
The dereference was too late.
2013-06-19 09:57:02 -07:00
Edwin Smith d7ee6388dd Split lvalPtr() into createLvalPtr/getLvalPtr()
Callers are always passing a constant to choose one or the other,
so make them distinct methods.
2013-06-19 09:57:02 -07:00
Paul Tarjan fe323e4821 add filter extension 2013-06-19 09:56:50 -07:00
mwilliams 49aa101879 Fix crashes with empty string as SetElem base
It needs to convert the key to a real TypedValue, and needs
to side exit (via throw).
2013-06-19 09:56:49 -07:00
Paul Tarjan 28bbefa14d actually implement SplObjectStorage 2013-06-19 09:56:39 -07:00
Paul Tarjan 09c916e585 make o_toBoolean non-virtual
I know this is bad form, but we need this for performance. Right now, o_toBoolean() isn't even being called. When D825610 lands it will be and will be a small perf regression.

If this situation gets bad, then we should revisit it, but since only one class is overriding it for now, this should be ok.

(I don't understand C++, did I do the virtual thing right? I had to declare them to make the linker work)
2013-06-19 09:54:37 -07:00
Eric Caruso 320babafb9 Match Zend behavior on openssl_pkey_get_details
Zend PHP populates an extra field in the details array
with some more information about the resource it is passed,
while HHVM leaves this information out.

Closes #815
2013-06-19 09:54:37 -07:00
Jordan DeLong 5a17a10cb6 TestExtOptions, TestExtNetwork, TestExtSocket -> php 2013-06-19 09:54:36 -07:00
Jordan DeLong fa3e93fdca Move TestExtMath to php 2013-06-19 09:54:36 -07:00
Jordan DeLong 4cebdbe47d Remove the ImageSprite extension
Believed to be unused now.
2013-06-19 09:54:36 -07:00
Sean Cannella 5a8d66a614 remove unused tx64 methods
remove dead tx64 code

due to sandcastle flakiness per bsimmers:
2013-06-19 09:54:36 -07:00
Sara Golemon 96caaa2e07 Bundle libmbfl filter files by default
Unicode.org's license allows us to redistribute these files
so long as they contain their original notice, so let's do so
and remove the need to download the files on every new checkout.

To force-update any file, just delete it and the build script
will download the most current version from unicode.org
2013-06-18 17:01:23 -07:00
Sean Cannella 6b2f9631b3 enable inlining for (most) static functions
- Enables inlining for existing function shapes for static calls except:
  1) static calls with a 'this' (as the refcounts become wrong)
2013-06-18 16:23:28 -07:00
Edwin Smith 6f8c436f66 Change HphpArray::m_lastE (an iterator) to m_used (a limit)
I made this change in my arrays working branch and liked it
enough to split it out and test/submit it early.  treating
the range of valid Elm slots as a vanilla open-ended range
[0..m_used) simplifies a bunch of code.
2013-06-18 16:23:28 -07:00
Sean Cannella 1b559a5364 remove unused files
remove unused files
2013-06-18 16:23:27 -07:00
Paul Tarjan 77cf51fb32 add session_register_shutdown
added in 5.4. The comments on http://php.net/manual/en/function.session-register-shutdown.php said this was equivilent.
2013-06-18 16:23:27 -07:00
Owen Yamauchi 49269952c8 Move everything out of GlobalNameValueTableWrapper
This is to clear the runway for getting rid of
GlobalNameValueTableWrapper. It moves aside these three items that were
in there for no particular reason other than convenience. I moved them
aside into another struct that I arena-allocate and initialize at the
same time as the global VarEnv (which initializes the GlobalNVTW).

I called the struct where these live "EnvConstants" since they look like
constants to PHP but their values are determined at startup time (by the
environment, like whether we're in server mode). lvalProxy doesn't fit
that mold, but oh well.
2013-06-18 16:23:27 -07:00
bsimmers 351d40d3d2 Transl::Tracelet -> JIT::RegionDesc converter
This converter enables much more thorough testing of the
region translator. It currently passes all tests, though it does punt
on one or more Tracelets in roughly 1/6th of them. The two big
unimplemented features for the whole pipeline are interpOne (should be
pretty easy) and parameter reffiness checks (probably
nontrivial). I'll attack those in separate diffs next.
2013-06-18 16:23:27 -07:00
Sean Cannella 019b649246 remove unused test code
removing unused code (supplanted by better assembler tests)
2013-06-18 16:23:26 -07:00
Sean Cannella c39053b32b cleanup annotation interface
Remove dead code, un-expose unused methods
2013-06-18 16:23:26 -07:00
Jordan DeLong 3add328e02 Fix slow/ext_url
Not sure why this passed in contbuild.  (It failed only on
the diff immediately after it ...)
2013-06-18 16:23:25 -07:00
Benjamin Strahs e35bded5b3 Add hash algos to openssl_verify
A bunch of hash algos are missing from openssl_verify(), this was fixed in PHP ( https://bugs.php.net/patch-display.php?patch=openssl-add-sig-algs.txt&bug_id=61421&revision=1340052451 ) and should be fixed in hhvm
2013-06-18 16:23:25 -07:00
Jordan DeLong 23ddfd8769 Port TestExtMb to php 2013-06-18 16:23:24 -07:00
Jordan DeLong 12b68dcd4b Port TestExtIpc to php
I don't like these ones very much.
2013-06-18 16:23:24 -07:00
Jordan DeLong 58f3a89039 Port TestExtJson 2013-06-18 16:23:24 -07:00
Jordan DeLong 32d985bb4d Port TestExtIntl 2013-06-18 16:23:24 -07:00
Jordan DeLong 75be029d31 Get the rest of the ExtIcu-ish things to php 2013-06-18 16:23:23 -07:00
Jordan DeLong 4795dcdc09 Migrate TestExtFile to php
I dropped a couple tests that did nothing
(e.g. clearstatcache) or almost nothing, or that 'tested' things that
almost all the tests do (e.g. unlink or fclose).  Dropped a few unixy
apis that really didn't test that they do anything.  Combined a few
tests also.
2013-06-18 16:23:23 -07:00
Jordan DeLong 877603b393 Convert most of TestExtMisc to php; delete rest
Removed all the tests that tested functions that just throw
NotImplemented, or actually did sleeps (without any testing that the
sleep actually did anything).  Otherwise about the same, but I had to
add some assumptions in unpack because you can't do sizeof() from php.
2013-06-18 16:23:23 -07:00
Jordan DeLong 79ce492c0d Port TestExtUrl to php 2013-06-18 16:23:23 -07:00
Jordan DeLong 99ce60eda7 Port TestExtIcu to php 2013-06-18 16:23:22 -07:00
Jordan DeLong 740998c959 Port TestExtIconv to php 2013-06-18 16:23:22 -07:00
Jordan DeLong c26c540024 Port TestExtPreg to php 2013-06-18 16:23:22 -07:00
Jordan DeLong 6d9262d63f Move TestExtHash to php 2013-06-18 16:23:22 -07:00
Jordan DeLong 74f217adcb Move TestExtBzip2 to a php implementation 2013-06-18 16:23:21 -07:00
Jordan DeLong e6052a08c1 Move TestExtXml{,Reader,Writer} to php 2013-06-18 16:23:21 -07:00
Jordan DeLong b95200c2d9 Remove several TestExt tests that did nothing or added no coverage
All did nothing except ExtFunction and ExtSimpleXml.
ExtFunction does things that are sufficiently tested in other suites.
SimpleXml has a test suite, and this only had a few calls to some last
error functions that seemed weak enough to delete.
2013-06-18 16:23:21 -07:00
Jordan DeLong e54398e418 Translate TestExtBcmath to php 2013-06-18 16:23:20 -07:00
Jordan DeLong 9d2faa74cc Move tests from test_ext_datetime to php 2013-06-18 16:23:20 -07:00
Jordan DeLong ee3d0c2d2d Move TestExtCType to php 2013-06-18 16:23:20 -07:00
Jordan DeLong 343f0b01f6 Port TestExtClass to php; delete TestExtClosure through Continuation 2013-06-18 16:23:20 -07:00
Jordan DeLong bda16ef85c Delete TestExtAsio
Empty stubs.
2013-06-18 16:23:19 -07:00
Jordan DeLong 2bbb036c66 Delete TestExtApd
It only tests that it is not implemented.
2013-06-18 16:23:19 -07:00
Jordan DeLong 606db54adb Remove TestExtThread
It doesn't really test anything.
2013-06-18 16:23:19 -07:00
Jordan DeLong 6c7cb9f55e Move test_ext_fb to php 2013-06-18 16:23:19 -07:00
Jordan DeLong 06a3a6b27d Delete TestExtSpl (it was empty) 2013-06-18 16:23:18 -07:00
Jordan DeLong 9e127b9831 Rewrite TestExtArray in php
Most of this is ported over, except some omissions:
  - array_filter, array_key_exists (suspected we had coverage already;
    one is a bytecode, and one was rewritten in hhas recently)
  - some random cases distinguishing init_null_variant vs. null_variant
2013-06-18 16:23:18 -07:00
Jordan DeLong e7d5f5d30f Move test_ext_{apc,apache} to php
Should include everything except I dropped:
  - anything that just tested we're throwing NotImplementedException
  - something about start_time() in ext_apc
2013-06-18 16:23:18 -07:00
Jordan DeLong a6854002c9 Fix hphp build
Not sure when this started happening, but it was getting an
unused but set variable warning.
2013-06-18 16:23:17 -07:00
Mike Magruder b24d2f2016 Unify multiple debugger client event loops, proper event handling in eval/print
There was a similar-but-different event loop used when receiving command results from the server which was close, but not quite right. Unified it with the main event loop to ensure that all error cases are handled properly when we put up a prompt at a nested interrupt, like when hitting a breakpoint during an eval. The event loop is now shared, with a few different "kinds" to control some of the special needs of the loop when executed from a command. Most  commands don't cause the server to run more PHP, so they don't change the machine state or cause more interrupts. But some do (Eval and Print) and certainly the top-level loop does, too. Made sure to throw a protocol error if any command causes this to happen when we don't expect it.
2013-06-18 16:23:17 -07:00
Herman Venter 902c13ed3e Disable test/quick/debugger/list.php
After a rebuild, the first run of the run/tests tests/quick/debugger/list.php invariably fails on developer machines. It passes if run again, or if another debugger test has passed before it has run.
2013-06-18 16:23:17 -07:00
Mike Magruder 22f8788e2f Cleanup client and server communication, events loops, and error handling.
Cleanup a lot of hangs with either the debugger client or server in a variety of error conditions, mostly related to communication errors or the client or server exiting unexpectedly. One of the biggest fixes is that all cases where the client was left in a state where Ctrl-C wouldn't work have been fixed.

Remove lots of little snippets of dead code. If you see a function (or small set of functions/fields) deleted then it was actually dead.

I debated whether to keep throwing DebuggerClientExitException on the server, and I decided to keep it. I think it's reasonable that if you've got the server stopped and you quit the debugger that the request gets terminated rather than continuing to run.

I also considered a big change to the way Ctrl-C works, but ended up staying with what was there with just a bit of cleanup. We need to guard against people banging on Ctrl-C, which is a reasonable behavior, and I think it feels pretty reasonable with the updated message.

Finally, added many comments about how this stuff works.
2013-06-18 16:23:17 -07:00
bill fumerola 8b80373f17 expose Vector->reserve(size) to php space
example usage: genv() takes a Vector of Awaitable and creates a
Vector of WaitHandles. resize() requires a default value, reserve allows us to hint proper allocation.
2013-06-17 17:31:33 -07:00
bill fumerola 4049e79f18 GenVector: it's likely the callers passed a proper Vector of WaitHandles 2013-06-17 17:31:33 -07:00
Eric Caruso 7ee2057a7d Revert "Adds word-size store instructions to x64 assembler" 2013-06-17 14:47:03 -07:00
Paul Tarjan 129b122972 revert timeout change
It looks like "timeout" doens't work on some machines...

  +sh: /usr/bin/timeout: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory
2013-06-17 14:46:27 -07:00
Paul Tarjan 66b2ef1e3b add timeout to test
One bad test shouldn't kill the whole run
2013-06-17 13:02:12 -07:00
mwilliams 3a6c6c286e Remove m_importMethToTraitMap from Class.
Its a temporary structure thats just used to help build the class.
Use it a local instead.
2013-06-17 13:02:12 -07:00
Jan Oravec c6f4e6b3c7 Recover from C++ exceptions in AsioExternalThreadEvent::unserialize(), part 2
AsioExternalThreadEvent::unserialize() may legally throw PHP exceptions.
When that happens, construction of PHP exceptions reenters VM, surprised
flag is checked and pending C++ exceptions may be thrown.

Let's make sure the queue of received events in runUntil() is not lost.
Move this responsibility to the AsioExternalThreadEventQueue.
2013-06-17 13:02:11 -07:00
Jan Oravec 797a6822d0 Move external thread event queue logic from AsioSession to AsioExternalThreadEventQueue
External thread event queueing logic is big enough that it deserves its
own class. Move the code and rename members to better reflect the
underlying operations. Implementation is otherwise unchanged.
2013-06-17 13:02:11 -07:00
Jan Oravec d6e869dfa9 Recover from C++ exceptions in AsioExternalThreadEvent::unserialize(), part1
AsioExternalThreadEvent::unserialize() may legally throw PHP exceptions.
When that happens, construction of PHP exceptions reenters VM, surprised
flag is checked and pending C++ exceptions may be thrown.

Let's make sure the event is properly destroyed. If it is not, the web
request will get stuck forever waiting for the finished event to finish.
2013-06-17 13:02:11 -07:00
Sara Golemon 27ef4c02cc Rename hphp/tools/gen-ext-hhvm to hphp/tools/bootstrap
gen-ext-hhvm actually contains three different
bootstrapping utilities:
* gen-ext-hhvm
* gen-infotabs
* gen-class-map

This move is just to give it a more contextually appropriate name.
2013-06-17 11:08:04 -07:00
Paul Tarjan 872c1d1bcf disambiguate symbols for Transl killing
I got stuck while trying to kill the `Transl` namespace, but these were the 'by-hand' changes I did before I got stuck. They get us closer so I think doing them will be helpful regardless.

Most were making longer names, but I also had to kill `Immed` (since there was another `Immed`in the other namespace). Originally I renamed it, but since them someone killed the last use of it.
2013-06-17 11:01:27 -07:00
ptarjan e48c95208d codify the instructions
People are using this to setup their machines. It should be more robust.
2013-06-07 22:14:00 -07:00
Sara Golemon 3a4defc30b Throw an exception when an unknown flag is specified
Because if we don't know, we can't fix it!
2013-06-15 23:32:09 -07:00
Sean Cannella e89645d960 Remove rematerialization code
- Remove rematerialization since it doesn't buy us much and we've had issues with it
2013-06-15 23:32:09 -07:00
Paul Tarjan 9f7b4a73c6 update mysql to a saner default
Most normal PHP programs will use mysql as an actual database, instead of the key/value store we use ours for.

It is hard to get a definitive answer on what the PHP default is, but I think it is 1 minute since it follows `default_socket_timeout` which is 60 seconds.
2013-06-15 23:32:09 -07:00
mwilliams 1626223e97 Avoid allocations for empty maps
Empty FixedStringMaps would do a malloc of at least 9 bytes,
and IndexedStringMap would do a 1 byte malloc, and a malloc of at least 9
bytes.

We have a lot of typically empty maps in our data structures.
2013-06-15 23:32:08 -07:00
Eric Caruso 5c787f5889 Adds decl and decw instructions that operate on registers
There was a confusing comment left in the assembler
that said that we can't encode a decl r32 instruction, because
the opcode is the same as a REX byte. This is untrue in our
assembler, because we use the FF /1 encoding, rather than the
48 one (which is a REX byte and would be a problem).

Some tests were added to show that this is fine.
2013-06-15 23:32:08 -07:00
Sean Cannella e7fc33d93f Inline simple printers (easier inline testing)
- Inlines simple constant print functions (makes it easier to test
inlining side effects in a simple manner)
- This also confirms that FPushObjMethodD inlining is working as expected
2013-06-15 23:32:08 -07:00
Paul Tarjan 613295121f make debug_backtrace 5.4 compatible
This was spewing on mediawiki and we need to update. It is backwards compat.

I tried to put the constants in PHP but failed. I spent 30 mins on it. I'll come back to it next time I get the itch.

Closes #812
2013-06-15 23:32:07 -07:00
Paul Tarjan 1ca7c026d1 Revert double thing
Some tests are failing now that didn't fail in contbuild. Revert until I can look at it.
2013-06-15 23:32:07 -07:00
Paul Tarjan 140c537a90 add JSON_UNESCAPED_UNICODE
This is giving warnings on wikimedia and was implemented in 5.4
2013-06-15 23:32:07 -07:00
Paul Tarjan 74b6e69086 fix what I broke with the double diff
I committed the wrong version.
2013-06-15 23:32:06 -07:00
Paul Tarjan 794f87542a try strtod instead of zend version
why is there a zend version and a c version? we mix and match in `is_numeric_string`. I'm worried this is giving me a problem in the filtering of floats.
2013-06-15 23:32:06 -07:00
bsimmers a4c8ea2957 Revert "Added AssertThis opcode and modified translator to emit it" 2013-06-15 23:32:01 -07:00
Paul Tarjan 0714b4e389 use a flag instead of isdigit
Instead of doing name-based checks, using a flag in the runtime seems better. I tried to have a flag on the FuncEmitter that was set when you made these weird functions, but there was a few situations that needed to do name-based checks

* .hhas files have no control over anything but the name
* the parser would have to pass the info through the AST to the emitter

Instead I opted for the simpler approach for now until we want to solve those.
2013-06-15 23:30:25 -07:00
Eric Caruso 1920e85155 Adds word-size store instructions to x64 assembler
Formerly, trying to emit a 16-bit instruction, such as
with test_imm16_disp_reg64(...) would actually emit a testl
instead of a testw. This would emit an 8-byte instruction
(ex. 41 f7 45 0e 01 01 00 00) and possibly be testing the wrong
thing. Now, when you emit a word-size instruction, it will prefix
with 66 and use the correct operand size, saving us a byte
(ex. 66 41 f7 45 0e 01 01).

I also converted the instruction emission in ContPreNext to
use the new style assembly emission.
2013-06-15 23:30:24 -07:00
Drew Paroski e6b6aa0b09 Clean up the hphp/system folder
I noticed that directorty structure of hphp/system was a bit scattered, so
I consolidated things to reduce the total number of folders and to put
related things together with each other.

This diff moves the contents of "hphp/system/classes_hhvm" into
"hphp/system", it moves the contents of "hphp/system/lib" into
"hphp/system", moves "hphp/idl" to "hphp/system/idl", and moves the
contents of "hphp/system/globals" into "hphp/system/idl".
2013-06-15 23:29:49 -07:00
Herman Venter 97f3015bb0 Add comments and type information to break_point
Non functional changes to make the code more readable.
2013-06-15 19:33:46 -07:00
Jordan DeLong f49b7f2e1c Delete various dead "currentRef"-related functions
endRef() is also almost dead, but not quite yet...
2013-06-15 19:33:46 -07:00
Jordan DeLong e11fd75d7a Remove Variant's o_foo member functions @override-unit-failures 2013-06-15 19:33:46 -07:00
Jordan DeLong f7d3d6511d Remove SmartAllocator support from Variant @override-unit-failures
It looks like this is all it takes now.  I couldn't find any
of the old .inc file stuff; I guess it went away at some point.
2013-06-15 19:33:46 -07:00
Jordan DeLong bb4ce81442 Remove NEW(Variant) uses in ext_mysql 2013-06-15 19:33:46 -07:00
Paul Tarjan bd8a697f13 fix text
oops
2013-06-15 19:33:46 -07:00
bsimmers f26cd669cc WIterNext and WIterNextK should break BBs
They're control flow instructions.
2013-06-15 19:33:45 -07:00
Jan Oravec 3ac5f621cd Recover from C++ exceptions
Recover from C++ exceptions so that PSP does not think ASIO is running. Fixes a segfault when ASIO fails on internal invariant violation in runUntil() with m_current == nullptr.
2013-06-15 19:33:45 -07:00
Edwin Smith d3601af2ac Remove StringOffset and String.lval() overloaded functions.
These are dead code, except for a few tests.
2013-06-15 19:33:45 -07:00
Herman Venter 4ed56d8a1d Parse nested namespaces in break point specifications.
Changed the parser for break point specifications to allow nested namespace qualifiers. Also extended this to the exception command.
2013-06-15 19:33:45 -07:00
Paul Bissonnette 5ee5fd8925 Added AssertThis opcode and modified translator to emit it
AssertThis is now emitted when IR is generated rather than simply
setting the isThisAvailable flag.
2013-06-15 19:33:45 -07:00
Paul Bissonnette c6ca429a5e Changed lookupIR in targetcache.cpp to not require a VMRegAnchor
Updated lookupIR functions in StaticMethodCache and StaticMethodFCache
to accept the FP as an argument.
2013-06-15 19:33:45 -07:00
Paul Tarjan d8386c9bc8 kill dead attributes
I was in here and noticed a few of them aren't used.
2013-06-15 19:33:45 -07:00
Paul Tarjan 419b03c787 clone config.hdf from slow to large_memory
It failed again with my other config.hdf commit already in the tree. Lets try the whole config I guess...
2013-06-15 19:33:45 -07:00
Herman Venter af0f28532a Cache the contents of systemlib.php for use by the debugger, if debugging.
Instead of calling get_systemlib every time the debugger client needs to list source from systemlib.php, use a cached copy of the source string. Only do this if debugging is enabled.
2013-06-15 19:33:45 -07:00
Owen Yamauchi e3ddc77159 Kill InclOpLocal
This one's an artifact of ReqMod and ReqSrc, which don't exist anymore.
2013-06-15 19:33:44 -07:00
Ben Maurer 69143a273c Possible Leak in UnitEmitter
I was looking at a jemalloc profile of HPHP ram and noticed
250 MB of RAM allocated from UnitEmitter::UnitEmitter. This
doesn't make sense since the memory is released on destruction.
I think that we're calling setBc which leaks the memory
2013-06-15 19:33:44 -07:00
Ben Maurer 27b22a4c6d Make libevent takeover support have better behavior when takeover not done
Currently, when we have takeover configured we don't close() the listen
socket until the hhvm process dies. This is bad because the loadbalancer
will continue to try to connect to the server and we will throw those
requests away.

This diff ensures that we always close the listen socket during server
shutdown.
2013-06-15 19:33:44 -07:00
mwilliams 866290d835 Fix crashes/assertions related to fb_intercept and reentry
If a function was called via (re)enterVM, and it didn't yet
have a prolog, and it was unable to get the write lease, and it was
intercepted, and the intercept handler asked for the original function
to be skipped, fcallHelper didn't return correctly, typically resulting
in the original function being re-executed, and then re-intercepted -
except that it was one level deeper in the vm-nesting hierarchy.

Eventually, it crashed.
2013-06-15 19:33:44 -07:00
Sean Cannella db9197d7a9 enable more failed inline shape printing
- profile inline shapes that fail due to IR compat reasons
2013-06-15 19:33:44 -07:00
Paul Tarjan 388ef5b984 back to 8 compile processes
I think they were running out of RAM
2013-06-14 15:56:02 -06:00
Paul Tarjan 5f5218836e use number of processors for compilation 2013-06-14 15:42:21 -06:00
Paul Tarjan a645427bce use number of CPUs on machine for tests 2013-06-13 16:34:43 -06:00
Sara Golemon c01bbf22de Translate gen_systemlib.php to bash
Remove another piece of PHP-dependant bootstrapping
2013-06-13 12:13:09 -07:00
Drew Paroski 7252c636ac Fix: Vector, Map, and StableMap should implement the Indexish interface 2013-06-13 10:25:47 -07:00
Jordan DeLong 7d9d87aee1 Revert "PolicyArray: implement NOT_IMPLEMENTED methods"
This reverts commit 1b65776a391188369a73dafca4851ba233e4e410.
2013-06-13 10:25:44 -07:00
Andrei Alexandrescu 1bfe90084a PolicyArray: implement NOT_IMPLEMENTED methods
This implements the "last" unimplemented methods in ArrayShell. The sorting-related methods need no implementation because PolicyArray scales to HphpArray before sorting.
2013-06-13 10:25:43 -07:00
Paul Tarjan fd8f503b18 more robust test
horribly broken things don't emit json
2013-06-13 10:25:43 -07:00
Paul Tarjan 5d47440dd1 add config.hdf to large_memory test
This probably needs a repo to check repo contention
2013-06-13 10:25:43 -07:00
Jordan DeLong f336f30911 Verifier: Fix a typo in switch bounds checking 2013-06-13 10:25:43 -07:00
Paul Tarjan 6e62230978 RecursiveFilterIterator
simple
2013-06-13 10:25:42 -07:00
Jordan DeLong 960f36f836 Restructure the unwinder a bit; use visitStackElems and simplify some things
Hopefully a little bit simpler, and duplicating less logic
with Stack::toString.  Contains some fixes to visitStackElems to make
it work for this (it is printing some stacks slightly incorrectly
right now, too ... :)
2013-06-13 10:25:38 -07:00
Jordan DeLong b01043bf3c Move the unwinder out of bytecode.cpp
Move all the stack unwinding code to its own module, delete
some redundant enumerations, document a few things.  Gets rid of most
of the remnants of the old setjmp/longjmp-based implementation at the
enterVM level but doesn't do much to the unwinder itself (coming in
separate diff to hopefully be easier to review).
2013-06-13 10:25:38 -07:00
Jordan DeLong 9e56c78038 Remove Variant::GetTypedAccessor
This stuff almost is an abstraction layer, but it's in a
strange place.  Also, the layout of TypedValue isn't something we've
been using through an abstraction layer, and if we want to later I
think we won't want to do so using this one.
2013-06-13 10:25:37 -07:00
Jordan DeLong d145ce88e3 Remove less, more, and equal functions from Variant
Re-implement them in terms of TypedValue and Cell helpers.
2013-06-13 10:25:37 -07:00
Paul Tarjan b2fb023ca8 use cpus+1 for tests
@swtaarrs says repo contention is a thing of the past and this is the right load to put on the cpu.
2013-06-13 10:25:37 -07:00
Owen Yamauchi fb930b9916 Delete reqLitHelper
It seems to have died with tx64.
2013-06-13 10:25:36 -07:00
Herman Venter 1cd7eb316e Check precondition before calling set_execution_mode
set_execution_mode has an assertion that amounts to a precondition requiring that its input parameters have been validated. This causes hhvm to assert and crash if the user specifies an invalid mode on the command line.
2013-06-13 10:25:36 -07:00
Herman Venter 2c37e4477e Port debugger unit tests for break command to new framework
Port debugger unit tests for break command to new framework to prepare for added many more tests dealing with nested namespaces.
2013-06-13 10:25:36 -07:00
Jordan DeLong cca68a7f91 Remove two unused builtin_functions.h things, collapse print() into echo() 2013-06-13 10:25:36 -07:00
Owen Yamauchi d7c2eac643 Get rid of variable break/continue
This is gone as of Zend 5.4: as far as I can tell, anything other than a
positive integer literal is a parse error (including constants, "1 + 1",
etc.) Let's get rid of it. The mere fact that this construct ever
existed in any programming language is deeply horrifying.

This lets us get rid of all the goofy code that subtracts 1 from the top
value on the stack, does IterFree if needed, and jumps to the next
level. Now, we can hardcode the necessary IterFrees and do a single
jump, right where the break/continue actually is.

The error message for using a non-integer expression is less helpful
than Zend's (Zend says "non-constant operand not supported"; ours is
"unexpected T_VARIABLE" or whatever). It wouldn't be that hard to do in
our parser, if we think that's helpful. I don't think it matters,
though.
2013-06-12 17:10:34 -07:00
Jordan DeLong bf72004e0e Remove some confusing assignments to NamedEntity::m_cachedClassOffset
Assigning this field is actually protected by the target
cache lock, and allocKnownClass does the assignment.
2013-06-12 17:10:26 -07:00
Paul Tarjan bd77ea909b try without recursion
see if we don't need it
2013-06-12 17:10:26 -07:00
Jordan DeLong 48346cb13d Remove lval(), id() and wrap_variant() from builtin_functions.h 2013-06-12 17:10:25 -07:00
Jordan DeLong a8a57b4b1a Remove concat5 and concat6 2013-06-12 17:10:21 -07:00
Sara Golemon 971f17421d Remove generator for system/constants.h which is now auto-built at compile time 2013-06-12 15:40:29 -07:00
Sara Golemon 13a055efa4 Add gen-class-map.cpp for bootstrapping constants.h and class_map.cpp
Conversion of PHP versions so we don't need PHP to build HHVM

For the most part, the generated files haven't changed from the
PHP sourced versions (apart from minor indentation and whitespace
changes).

Except for one major exception:
An IDL's function/method argument list includes a "value" field
for default parameters which takes psuedo-serialized values in
several forms. Most are simple scalarish values like:
  "true", "null", "null_array", "null_variant",
  "123", "0x456", "0123", "1.23", "\"foo\""
However referencing other constants is also supported:
  "k_FOO", "q_Bar$$BAZ"
Or even bitmask compositions like:
  "k_FOO|k_BAR|k_BAZ"

Runtime uses of these values are encoded directly into *.ext_hhvm.cpp
files, so they reach userspace code just fine.

The value placed in g_class_map are used exclusively by ext_reflection
to allow introspection at runtime.  Under the old class_map.php parameter
default constant references would be resolved in a (somewhat buggy) eval(),
since we don't have eval within gen-class-map, we reuse the
kUnserializable deferral.

This diff provides a mechanism to resolve this in ReflectionMethod
uses (an improvement from previous behavior), and leaves the current
eval-on-demand behavior for ReflectionFunction.  These two code paths
are different due to the partial state of migration away from using
ClassInfo.
2013-06-12 15:38:53 -07:00
Jan Oravec 8491515257 Kill InlineCreateCont
Remove unnecessary optimization that can be achieved in a more general
way and simplify continuation creation code.

VMExecutionContext::createContinuationHelper was renamed to
VMExecutionContext::createCont{Func,Meth}. The createContFunc no longer
takes this/class arguments, the createContMeth transfers them in one
Type::Ctx pointer that is used natively by ActRec's m_this. Since the
whole logic of this function is to set this single field, the logic is
now simpler.

Interpreter: iopCreateCont() just passes the m_this field of the parent
ActRec.

Translator: CreateCont opcode loads m_this field using LdCtx opcode.
This opcode optimizes into LdThis, which optimizes into
DefInlineFP->SpillFrame->object and allows frame to be eliminated, a
case previously covered by InlineCreateCont.

This diff uncovered a bug in trace builder, where LdCtx in static
methods could be optimized into LdThis, if the method was called thru
object. Fixed.
2013-06-12 14:04:05 -07:00
Paul Tarjan fca204fd63 add slow tests
with the repo contention test moved, these now all pass
2013-06-12 13:51:10 -06:00
Owen Yamauchi 79224cdd38 Remove the hardcoded globals from GlobalNameValueTableWrapper
The ultimate goal is to de-virtualize ArrayData. To do this, we need a
single ArrayData subclass that has all the capabilities we need. This
2013-06-12 11:35:00 -07:00
bsimmers cf87b7eec3 Basic region translator
This diff adds a very, very basic region translator. Together with
-vEval.JitRegionSelector=method, it is capable of translating very simple
methods without using a Tracelet. It takes in a RegionDesc struct and creates
NormalizedInstructions on the stack to drive the translate* methods in
irtranslator.cpp. I started trying to get all tests passing with
JitRegionSelector=method (by replacing lots of asserts with punts) but decided
it's not worth it right now.

I'm planning on writing a Tracelet -> RegionDesc converter next and expanding
translateRegion to handle everything that throws at it.
2013-06-12 11:34:41 -07:00
Edwin Smith 274ef6c45b Split ArrayData::append(ArrayOp) into plus() and merge()
We had two distinct functions dispatched by an enum that was
always known somewhere higher up on the callstack.
2013-06-12 11:34:41 -07:00
Paul Tarjan b0de59da49 move repo contention test
I'd like to run the slow tests in our open source testing framework. This is the only test that fails hard. It actually fatals the test framework even with the 10 Meg limit we are using now.

What do you think about breaking it out to not run in open source?
2013-06-12 11:34:40 -07:00
Paul Tarjan 6d109c37c2 only accept ports in range
http://example.com:-1 isn't a valid url
2013-06-12 11:34:40 -07:00
Paul Tarjan e8aa945337 fix pathinfo
This is needed for CodeIgniter. They do `pathinfo()` and triple equal compare to "".
2013-06-12 11:34:40 -07:00
Jan Oravec e8acd400ac Remove unused UnitEmitter::m_feMap
The value of m_feMap is never used. Keys are used to assert when there
is an attempt to define a function with already existing name. It does
this job poorly because it is not an authoritative source of existing
function names. When the top-level function is defined, setCached() is
called, which already checks for duplicates, so let's rely on it.
2013-06-12 11:34:39 -07:00
Paul Tarjan e3d31d70de fix StaticString copy constructor 2013-06-12 11:34:39 -07:00
Paul Tarjan 269ec416d5 Rename closures and generators - take 3
This reverts commit 2e9677b7c3f37e9627b9cbc9a6ddec82a10e7215.

Third time is the charm. I hid it from reflection, but I missed `get_class_methods`.

The diff betweenn this and what was reverted is https://phabricator.fb.com/P2217891 and then I did https://phabricator.fb.com/P2217904 because it looked like it should be done.
2013-06-12 11:34:39 -07:00
mwilliams 8069424449 Fix order dependencies in BuiltinSymbols::Load
We need to import the c++ classes and constants before parsing
systemlib.php so that static analysis is aware of them.
2013-06-12 11:34:39 -07:00
Herman Venter d160ad4ddb Source information for systemlib.php for use in debugging.
The debugger can only hit breakpoints and list source lines for code lines that have an entry in the byte code repository. In order to make systemlib.php debuggable, it needs an entry. A customized routine has been created for doing this since there is no actual source file available. Also, special case logic is needed to list the source file during debugging.
2013-06-12 11:34:38 -07:00
Herman Venter 6a0d728a8a Add tracing to cmd_run and the debugger API
Add some tracing to help with debugging the debugger API.
2013-06-12 11:34:38 -07:00
Mike Magruder 5d25a36a61 Remove the rest of the dead instrumentation code
This is the follow on to https://phabricator.fb.com/D805320. Removing the rest of the instrumentation code.
2013-06-12 11:34:38 -07:00
Edwin Smith d44d103886 Keys can't be doubles: remove a bunch of Array/Variant methods.
Array and Variant don't need to accept double for array keys,
since they can only be int or string anyways.  The only place
we called those methods was in test_cpp_base.cpp anyway.
2013-06-12 11:34:38 -07:00
Jordan DeLong 08ea36967e Delete all non-CVarRef overloads of empty/isset @override-unit-failures
We only really use those now.
2013-06-12 11:34:37 -07:00
Sean Cannella 333f0a76f4 Fix a zend compat issue in array_slice
- Fix the behavior of array_slice when using PHP_INT_MAX
2013-06-12 11:34:37 -07:00
Jordan DeLong fd657cfeb8 Remove mostly unused instanceOf() function
We don't need to overload this on types anymore.
2013-06-12 11:34:37 -07:00
Jordan DeLong 27faa44c30 Delete same() overloads that don't involve VM types
Don't really need these anymore now that we're not generating
C++.
2013-06-12 11:34:37 -07:00
Jordan DeLong 3e188a56dd Prune some unused/barely used functions from type_conversion.h @override-unit-failures 2013-06-12 11:34:36 -07:00
Jordan DeLong d8bddea335 delete Variant::same, implement same(CVarRef, CVarRef) in terms of tvSame
Step two.  Leaving the Variant::same methods as deleted for
now because I'm worried about the implicit conversion operators to
other types that support same.
2013-06-12 11:34:36 -07:00
Jordan DeLong 2618ad0ef2 Delete all the non-variant Variant::same overloads
Step one.
2013-06-12 11:34:36 -07:00
mwilliams 412dce677f Better reffiness checks
While debugging a sandbox crash, I spent some time looking at a huge
sequnce of conditional masks, compares and branches that didnt seem
to belong in the code I was debugging. Finally realized that it was
a reffiness check. It looked way too complicated, so I investigated.

Part of the problem was that we were avoiding a malloc in the case
of a zero param function at the expense of an extra check.

Instead, this diff always sets up at least 64 bits worth of m_refBitVec.
But by using the space set aside for the pointer in Func::m_shared it
avoids a malloc for any function with fewer than 65 arguments, and
avoids the numParams check for the first 64 parameters.

In addition, the existing code was spitting out a generic test for
the guard condition - (mask & bits) == value - where mask and value
are known constants. Since the most common case is that value == 0
(all the parameters are expected to be by value), we can usually omit
the compare. In addition, since most functions only have a small
number of parameters, we can usually get away with 8 bit, or 32
bit operations.

The result is that for a typical function (fewer than 64 args, args
expected to be by value) the reffiness guard is now

  test <mask>, Func::m_refBitVec[0]
  jne exit

Rather than:

  move <mask>, reg1
  xor reg2, reg2
  cmp 1, Func::m_numParams
  jnl ok
  test AttrVarArgs, Func::m_attrs
  jne exit
  jmp done
ok:
  load reg3, Func::m_refBitVec[0]
  and mask, reg3
  cmp reg3, reg2
  jne exit
done:
2013-06-11 11:48:25 -07:00
mwilliams 94ad2fd0ee Fix TestExtSocket flakiness
It picked a random starting port, then incremented
for each test. If it happened to collide with an existing
port, it failed. Make it try 20 different ports before giving
up and failing.
2013-06-11 11:48:25 -07:00
mwilliams b967e102a0 Get rid of BuiltinSymbols at runtime
We were using BuiltinSymbols at runtime to identify
potential FCallBuiltin sites. Instead, we can lookup the Func*,
which already has all the information we need.
2013-06-11 11:48:24 -07:00
Jan Oravec 9662396bf0 Store variable arguments in optional local
Save 8 bytes of m_args and its initialization for Continuations without
func_get_args() call (does not save real memory due to 16-byte alignment).
Store variable arguments in optional local.
2013-06-11 11:48:06 -07:00
Dario Russi f6de025eab Optimize FPassM for Vector and Map
Added FPassM to the instruction optimized for Vector and Map. It reuses the code for CGetM.
2013-06-11 11:47:48 -07:00
Paul Bissonnette d8df647b38 Fixed cleanup/exception handling for vector operations.
Vector statements ending with a SetProp now properly free
         memory when run with JIT enabled.  Additionally, in both
         JIT and interpreted mode memory will still be freed if
         exceptions are thrown during evaluation of vector operations.
2013-06-11 11:47:47 -07:00
Drew Paroski 9b95c48416 Fix issue with XHP and keywords 2013-06-11 11:47:47 -07:00
Mike Magruder c158e4a24b Cleanup small stepping
Small stepping, which is stepping over sub-expressions (kinda), worked but was a little goofy. The mode was set on the client, passed over with control flow commands, placed on the execution context, then retrieved from there and used by those same flow commands. Removed the execution context part of it, since it was useless, and factored grabbing the offsets into the flow cmds where they belong instead of doing it all the time.

The run cmd also had some notion of small stepping, but you'll note it was never sent over the wire. Nuked that, since it never mattered anyway.
2013-06-11 11:47:28 -07:00
Drew Paroski eaabed2416 Fix deep copying for Sets
This logic got messed up somehow during rebasing and we were missing a
case for Set inside collectionDeepCopyTV(). This diff fixes the issue.
2013-06-11 11:47:28 -07:00
Herman Venter da8e8adc46 Add back a necessary null check
Diff 817612 added a null check, but inadvertently removed a null check.
2013-06-11 11:47:28 -07:00
Paul Tarjan d5ee17487a allow constants in systemlib
The problem was a few:

* All constant declarations were wrapped in a statement list. The merge-only check was allowing top-level `define()`s but not top level statement lists. I unwrapped them. I have no idea why it was done. Probalby just cargo cult programming.
* When converting a UnitEmitter to a Unit we only allowed constants in RepoAuthoritative mode and not systemlib mode.
* Systemlib constants weren't being set as UnitMergeKindPersistentDefine
* UnitMergeKindPersistentDefine constants weren't being marked mergeOnly when pulling out of a repro
2013-06-11 11:47:28 -07:00
Paul Tarjan 18067c4020 don't call auotloader with blank name
I debated putting in an assert in the autoloader but I'm worried that will break many things. Lets just plug this for now.

Closes #803
2013-06-11 11:47:08 -07:00
Dario Russi fe8b84f542 vector and map get/set/isset specialization in IR
specialized the IR instruction CGetM/SetM/IssetM for Vector and Map. IR now generates specialized code in those situation similar to what is done with Array.
2013-06-11 11:47:07 -07:00
Edwin Smith 51967b2c12 Remove ArrayData::getIndex virtual methods.
They aren't used anymore, except to implement isVectorData(),
which we can make pure-virtual and implement more efficiently
in each subclass of ArrayData.
2013-06-11 11:47:07 -07:00
Mike Magruder eec54a0f6c Cleanup a bit of exception/error handling between the VM and the debugger
We had two similar-but-different functions for getting a notification from the VM about an exception. Cleaned that up by using the proper one for a thrown exception where appropriate, and moving the old one into a hook (like the other VM->debugger hooks) specifically for error messages.
2013-06-11 11:47:07 -07:00
mwilliams 7398db6097 Keep the uploaded data when a partial upload error occurs
When we get an UPLOAD_ERROR_C, record the filename and the size
as usual.

I've not been able to test this - I can't get a partial uplaod,
even by quitting from firefox during the upload. I seem to either
get a full upload, or nothing at all.
2013-06-10 10:14:13 -07:00
Paul Tarjan 8cf6ccb00a use TRACE_SET_MOD
I found this macro while refactoring and since I like consistency, I used it everywhere.
2013-06-10 10:14:13 -07:00
Paul Tarjan 1b47c9fdd2 fix header order
fixed the lint rule and includes the extra header we needed
2013-06-10 10:14:13 -07:00
Herman Venter a2d949f9d2 Do not recreate the debugger options file.
The code for reading in the personalized debugger options, always wrote out the file to account for the case where there may not be a file in the first place. This is not necessary and can lead to the file being changed when running various kinds of debugger tests. Since the tests use a checked in file, it is not desirable for the file to change as a result of a test run. With this change, the file will only be written out when it is missing in the first place. There are still some scenarios where it is possible to write a test that will change the file. Currently no such tests exist. Also, in those scenarios, the test may well want to verify that the file is changed, so more work will needed later on. Right now, that can wait.
2013-06-10 10:14:13 -07:00
Herman Venter fcf0c7533c Remove assertion that is no longer true and that does not do anything useful.
This assertion should have been removed with an earlier diff that made it no longer true.
2013-06-10 10:14:12 -07:00
Edwin Smith f69a002911 Remove the SharedVariant pointer from StringData.
We only use it to lazily grab the hashcode.  So just grab the hashcode
eagerly when we create the string.
2013-06-10 10:14:12 -07:00
Herman Venter 3d0330fd9d Provide a command line switch to specify the path to the debugger config file
Currently the debugger config file is always expected to be at ~/.hphpd.hdf, except when the debugger is controlled via the API, in which case the API client can specify the path. With these changes the path can now also be specified via the command line. Also, the test runner has been modified to look for an hphpd.hdf file and specify the path to it as a command line option. If present, this file also indicates that tests in the directory must be run in debugger mode, making the .opt files redundant. Note that it is important for tests to be able to control the contents of the config file since debugger output is controlled by it and tests will be brittle unless the config is part of the suite and not controlled by the user running the tests
2013-06-10 10:14:12 -07:00
Paul Tarjan a729338538 Trace -> IRTrace
For converting Transl -> JIT. We either do this or convert all the other `Trace` calls to `HPHP::Trace` which seemed worse. This also niecly mirrors `IRInstruction`.
2013-06-10 10:14:12 -07:00
Paul Tarjan 1c50cae763 s/Call/CPPCall/
A precursor to moving the Transl namespace to JIT. We have an IR opcode `Call` and this would conflict. Those should probably be in another namespace, but this is easier.

This was way easier to do in a compiled language :)
2013-06-10 10:14:11 -07:00
Mike Magruder 96d6bab291 Cleanup flow control around exceptions
There were multiple issues with flow control when exceptions occur. Fixed these by ditching the reliance on the exception thrown interrupt and introduce an exception handler interrupt, which indicates control is about to pass to a catch clause. This gives us much better insight into how execution is flowing and how we might need to adjust an in-flight stepping operation.
2013-06-10 10:14:11 -07:00
Sean Cannella 4c26494f85 Make Nemo aware of functions defined in systemlib
Now that we define functions in systemlib they also need to be available during static (Nemo) analysis.
2013-06-10 10:14:11 -07:00
Paul Tarjan 7b6d06074c just thorw a regular exception
I'm not expecting a user to do anything actionable (other than open an issue) on this error so a regular Exception should be ok.
2013-06-10 10:14:11 -07:00
Paul Tarjan 0d3eaf9fd3 add irc notifications 2013-06-07 17:53:59 -06:00
Paul Tarjan 83b310a20f try more threads now that there is less used ram 2013-06-07 15:27:35 -07:00
Paul Tarjan bcefd15d4e change amount of memory tests can use 2013-06-07 14:24:34 -07:00
Sean Cannella 543927cc35 make PHP_SAPI dynamic based on execution mode
It isn't really a constant anyways.

Closes #757
2013-06-07 12:41:50 -07:00
Herman Venter 894b0addf2 Provide a config option to turn off debugger prompt.
The debugger prompt string depends on user/machine specific configuration settings, which makes its inclusion in expected test output problematic. There is already an option in (the user controlled) ~/.hphpd.hdf to turn off the prompt. Now there is an option in normal config files to do the same.
2013-06-07 12:41:30 -07:00
Jan Oravec 1d90b368dc Kill m_localsOffset and free another 16 bytes of memory
Users of m_localsOffset used this offset to calculate pointer where
local variables starts. Since they are stored in the reverse order, the
equation was:

  cont_ptr + m_localsOffset + num_locals - local_id - 1

We are already storing pointer to ActRec (m_arPtr), which is equal to:

  cont_ptr + m_localsOffset + num_locals

This diffs kills m_localsOffset and uses m_arPtr to simplify
calculations. Continuation fields were rearranged so that
sizeof(c_Continuation) is reduced by 16 bytes.
2013-06-07 12:41:30 -07:00
bsimmers aa509ef3b9 Clean up TranslatorX64
This is a bunch of cleanup I've done for my work on the
region translator that isn't strictly releated to the region
translator.

- Move irTranslate* methods up to Translator and rename them
  translate*.
- Remove a bunch of friend declarations from TranslatorX64.
- Remove emitVariantGuards. We don't translate pseudomains so it was
  never doing anything anyway.
- Remove the unused REQ_BIND_REQUIRE.
2013-06-07 12:41:30 -07:00
Edwin Smith 4fac83a847 Remove dumpDebugInfo (dead code)
it's dead
2013-06-07 12:41:30 -07:00
Edwin Smith c5fed85723 Delete unused litstr conversion functions
These aren't called, so this takes them off the table.
2013-06-07 12:41:29 -07:00
Paul Tarjan f5569e4755 clean up tests dir
I think this dir shouldn't have anything non-necessary in the root.
2013-06-06 16:31:09 -07:00
Jordan DeLong dc6dc022e7 Initial API for region selectors
Contains some structures to use for communicating between
compilation region selectors and the JIT.  For now includes two
debugging-oriented region selectors, one that uses a single HHBC
opcode at a time, and one that blindly pushes in the whole CFG for a
method using the Verifier::GraphBuilder.
2013-06-06 15:58:14 -07:00
Jordan DeLong e05dd4e9ff Make stack walking logic from Stack::toString reusable
I need to walk a live eval stack, handling FPI regions and
generators, and duplicating that logic in yet another place seems
wrong.  This makes the Stack::toString stuff use a reusable one---at
some point I'll see if the unwinder can use it as well, but it works
also for my use case.  Also, Stack::toString was broken for mutable
array iterators---fixes that.  And use a union now for struct Iter.
And don't include bytecode.h from func.h.
2013-06-06 15:58:14 -07:00
Jordan DeLong 51574fb2ec Fix an assembler bug with FPI region offsets
The assembler recorded the offset to FPI regions based on the
stack depth before the instruction executed.  This is trivially wrong
for instructions like FPushCtorD, but also breaks in nested FPI
regions.  The assembler is tracking fdescDepth independently of the
eval stack, so as long as we continue to require that all FPush* ops
logically push the ActRec *after* all their other pops and pushes,
this fix should work.  It might be nice to some day reword the
bytecode.specification stuff to include ActRecs as part of the eval
stack, though, so it isn't ambigious which order they happen for the
FPIEnt offsets.
2013-06-06 15:58:14 -07:00
mwilliams adee83bab7 Run repo-authoritative tests in repo-authoritative mode
Because its the right thing to do. Even if some tests fail.
2013-06-06 15:58:13 -07:00
Jan Oravec c839f3c3d0 Fix static variables in closure generators
Each closure instance carries its own set of static variables. Multiple
generators created using the same closure instance should share their
static variables.

This was not the case and static variables in closure generators behaved
like normal local variables. Let's fix it by referencing closure and
using its static locals.

Pointer to the closure is located in the local following original input
arguments. These are shifted by one, as Continuation occupies local 0.

This also frees 8 bytes from c_Continuation (or 16 if you count 16-byte
alignment).
2013-06-06 15:57:06 -07:00
Jan Oravec 1e48e96bbe Remove m_obj from c_Continuation
m_obj in c_Continuation is redundant. It is only used at the time
Continuation is created. First, it is set in init() call. Few
instructions later, it is read so that $this in the Continuation's
ActRec can be populated.

Kill it.
2013-06-06 15:57:06 -07:00
Edwin Smith 3515793e74 Remove ArrayData::nvSet() wrappers and several dead Array helpers.
nvSet() only casts the value from TypedValue* to const Variant&; do it
at callsites.  Inlined array_setm_ik1_v0() and array_setm_s0k1_v0() into
their only remaining callsites in translator-runtime.cpp.
2013-06-06 15:57:05 -07:00
Paul Tarjan 20ad8ba931 fix SplFileInfo->openFile
without a default class, opening a file doens't work so well

Closes #802
2013-06-06 12:00:08 -07:00
Eric Caruso 958df942ce replicating readline control characters in test output
Readline is awful and dumps characters in the output.
This was causing tests to act weird on another build.
2013-06-06 12:00:07 -07:00
Eric Caruso 9b750620a7 Clean up some header includes 2013-06-06 12:00:07 -07:00
mwilliams 70751f99a8 Fix a bug for continuations-from-closures that need a local $this
If a continuation in a closure needed a $this variable,
hhir would fail to initialize it, resulting in reads reporting
null.

This didn't come up much, because usually we dont need a variable;
we can typically use This or BareThis. Its only cases where $this
might be passed by reference, or there are dynamic variables that
actually require a local $this.
2013-06-06 12:00:07 -07:00
Andrei Alexandrescu 4debf268f7 ArrayData: consolidate m_nonsmart and m_allocMode into one field
The in-situ allocation case can be easily detected by checking m_data == m_inline_data.slots. Therefore there's no need for two distinct flags to track current and future allocation strategy.
2013-06-06 12:00:06 -07:00
Edwin Smith fe32089a67 Reduce use of AttachLiteral StringData construction
This is the first results from profiling callsites of
StringData::initLiteral.  This diff converts a handful more
string literals to StaticString, removes overloaded Variant
comparison operators (operator==, etc), and avoids
constructing new strings in a few cases in tvCastToString
and tvCastToStringInPlace.
2013-06-06 12:00:06 -07:00
Jan Oravec 611e80011a Remove unneeded EmitterVisitor::m_methLabels
EmitterVisitor::m_methLabels is used for 2 purposes:

- avoid emitting generator body twice
- fatal at the import time when file contains already defined function

The labels themselves are not used as labels, comments suggests it used
to be used for fast calls.

Replace them with 2 dedicated sets: m_generatorEmitted flag for generator bodies, m_topMethodEmitted for functions.
2013-06-06 12:00:06 -07:00
Eric Caruso 006d2da96d Added warning for bad return values from user comparators
Alerts users that comparators should be in the
style of functions passed to e.g. C qsort (i.e. returning
-1, 0, or 1) rather than STL-style boolean comparators (i.e.
true for less-than).
2013-06-06 12:00:05 -07:00
Jordan DeLong fa6f3f7e12 Implement most of class_alias
Throws the aliased class into a target cache slot for the new
name.  Handles errors when you try to re-alias a class, but doesn't
restrict a few other cases zend does:

  - If you implement an interface twice, zend complains (one of the
    alias tests checks this).  I tried turning it on, but we violate
    it in systemlib currently so I left it off.

  - class_alias_014.php does some namespace stuff I don't quite grok.
    (@ptarjan let me know what to do if it's easy).

  - inter_007.php uses class_alias, but is testing a warning that
    happens even with out it.  (We don't raise this warning.)

  - zend raises a warning if you try to class_alias a non-user-defined
    class; I left this out.
2013-06-06 12:00:05 -07:00
Edwin Smith 34a52f49f5 Array::add(), set(), and setRef() don't need to return anything.
Removes a bit of code, and avoids a few uses of lvalBlackHole().
2013-06-06 12:00:04 -07:00
bsimmers 6fca89f259 Disable flaky zend test
I've seen it failing on master intermittently
2013-06-06 12:00:04 -07:00
Bert Maher bf52b61852 Allow early initialization of classes if they don't have any [sp]init methods
We were being too conservative in determining whether to use
the static property cache when accessing a property from outside the
class.  In fact we'd never use it in that case, because we required
that the class not need initialization (and any class with static
properties needs initialization!).

We can relax this restriction to just enforce that the class not
define sinit or pinit methods -- scalar properties are fine.
2013-06-06 12:00:04 -07:00
Jordan DeLong bcc0192c13 Improve verifier error message marginally (include unit, func) 2013-06-06 11:59:56 -07:00
Paul Tarjan ec6f051b0b fix bug36258
Now that contbuild summaries work, it is so much nicer.

I'm trying to use the property in a child. Either a keep the data around or make the parent's protected.
2013-06-06 11:39:15 -07:00
Edwin Smith de080dbc75 StackTraceProfiler utility class
StackTraceProfiler is a utility class for collecting call-stack profiles
at specific places in the code.  Typical use is to create a static
instance, then call prof.count() under the desired conditions.  You
can of course compose these to make value profilers.
2013-06-06 11:39:14 -07:00
Paul Tarjan 43da51882c fix argv in server mode
Match zend.
2013-06-06 11:39:14 -07:00
mwilliams 7f77095315 Fix asm_test
SimpleLableTest used rbx, r10, r11, r15 without saving them,
causing lots of potential issues.

RandomJunk relied on white space at the end of a line - but our
master.emacs is setup to strip trailing space on save. I rewrote
the test to avoid having to remember to override every time.
2013-06-06 11:39:14 -07:00
Mike Magruder 87ff333281 Add support for debuggers and continuations to out2expectf.py
Added something specific for the debugger to sanitize the relative paths of the debugger tests. Also added sanitization for continuation functions names.
2013-06-06 11:39:13 -07:00
Andrei Alexandrescu a2e76eb7b2 Eliminate static noise from .h files
The codebase had several namespace-level static data definitions and function definitions. Using namespace-level "static" in a .h file is near-always a bad idea, as follows:

  - for simple types, static is implied. Example: "const int x = 42;" is the same as "static const int x = 42;"
  - for aggregate types, static linkage implies that a copy of the aggregate will appear in every compilation unit that includes the header.
  - for functions, static means the function will have a separate body generated in each compilation unit including the header.
  - in several places functions were defined 'static inline', which is just as bad. 'inline' is just a hint which means the function may end up having a body (and actually more due to 'static').

True, gnu's linker has means to remove duplicate definition, but that's not always guaranteed or possible (think e.g. static functions that define static data inside, ouch). So static is useless at best and pernicious at worst. We should never, ever use static at namespace level in headers. I will create a bootcamp task for a lint rule.

I expected the performance to be neutral after the change, but in fact there's a significant drop in instruction count and therefore a measurable reduction in CPU time: https://our.intern.facebook.com/intern/perflab/details.php?eq_id=431903
2013-06-06 11:39:13 -07:00
mwilliams 310884d8f1 Don't crash trying to print bytecode for unreachable switch targets
In some circumstances, the label associated with a branch
doesn't get set, and the corresponding branch target ends up pointing
to one byte before the start of the unit's bytecode.

In that case, we were crashing when trying to dump the bytecode.
2013-06-06 11:39:13 -07:00
mwilliams 2a36ee1405 Free Func's properly
Func's are allocated using Util::low_malloc, so need to be
free'd with Util::low_free, rather than boost::checked_deleter.

In addition, there is some munging of the Func address going on,
so we really need to call Func::destroy instead.
2013-06-06 11:39:12 -07:00
Paul Tarjan e433cd193c move compiled tests files into another dir
I've been linking people to the README in this directory, but it is hard to see with all these files in here. What do people think about it moving a subdirectory? I don't love the name.
2013-06-06 11:39:06 -07:00
Sean Cannella 64e24977ca STD* streams should not be defined in server mode
- Zend doesn't define STDIN/STDERR/STDOUT in server mode, neither should
  we
2013-06-06 11:08:39 -07:00
Jordan DeLong 4e547faa8f Verifier: disable iterator checks, turn verifier on for systemlib @override-unit-failures
It's better to have some checks than none.  The only checks
failing in systemlib are iterator lifetime things, which it seems like
we're not about to fix.  Run the verifier on systemlib but only in
debug builds.
2013-06-06 11:07:59 -07:00
Herman Venter 917fffb462 Reduce redundant spew when breaking on an unhandled exception. Quit cleanly.
Currently the debugger prints the line where an exception has been thrown, along with the type exception. Then it prints the source listing of the exception. Then it prints a serialization of the exception, which includes a full stack trace. Since the debugger has a command for printing stack traces, the latter bit information seems completely redundant when stopped in the command line client. This diff suppresses the stack trace in that case. It also suppresses redundant diagnostics that get generated during the debugger's attempt to find and print the source code in response to a list command. Finally, the quit command was too eager to let the client die after notifying the proxy, causing the proxy to get a pipe closed exception rather than the quit command, which often allowed the program to carry on running after the client has already quit. The quit command now waits for an acknowledgement from the proxy before shutting down.
2013-06-06 11:07:59 -07:00
Owen Yamauchi 3e26291f90 Fix missing header
Some systems (my ARM SDK) seem to need this.
2013-06-06 11:07:58 -07:00
Mike Magruder da03bc9353 A few step out fixes
Fix counted step outs, and add a test for all counted stepping commands.
2013-06-06 11:07:58 -07:00
Paul Tarjan 4d642e9cd7 test runner fixes
* Put `details` in the ending results output. Hopefully that appears on diffs.
* Exit early if we can't invoke the command (and abuse the `.diff` file).
* Error out if any output is on stderr.
* Fix the diff for regex tests (not that we have many).
* Capture stderr when running `hphp`
* Parse out FAILED: line during jenkins
2013-06-06 11:07:58 -07:00
Paul Tarjan d1baeadc65 update link to CLA
we will use the individual one most commonly
2013-06-04 18:01:44 -07:00
mwilliams d62fddec07 Fix crash in array_filter/array_map with a bad function
interp only
2013-06-04 17:53:38 -07:00
Jordan DeLong 82095e9227 Unconditionally run the verifier on hhas files; fix various errors @override-unit-failures 2013-06-04 17:53:38 -07:00
Jordan DeLong 0a18064197 Add some unique_ptr-related support to smart:: containers
- smart::make_unique, returns a unique pointer to smart allocated
    data.

  - Support forwarding in our allocator's construct, so
    smart::vector<foo::unique_ptr<>> works.

  - Move smart containers to their own header.
2013-06-04 17:53:38 -07:00
bill fumerola d139011517 GenVectorWaitHandle
add GenVectorWaitHandle, a WaitHandle suitable for use with the Vector collection.
2013-06-04 17:53:38 -07:00
Guilherme Ottoni 5a76c92c73 LdClsCns's dest is Uncounted
So annotate that when generating the IR instruction and clean-up isRefCounted.
2013-06-04 17:53:38 -07:00
mwilliams 99f3924872 Fix an issue with fb_intercept
After my rewrite to use the FunctionnEnter hook to implement
intercept, there was a potential problem.

If an intercept handler was intercepted, and we hadn't yet jitted
the prolog for the intercept handler, and we lost the race to jit it,
and the intercept handler threw an exception, the unwinder could skip
some c++ frames, and fail to unwind a re-entry.

This was caused by attempting to emulate the previous intercept
behavior, where the original function is not included in the backtrace.
I don't think thats necessary; for one thing, the intercept handler
has always appeared in the backtrace, even though its (generally) not the
replacement function, but a function that forwards to the replacement
function. So this diff just leaves the original function's fraem in place.
If the backtraces *do* turn out to be problematic, I'll fix it later in
debugBacktrace.
2013-06-04 17:53:38 -07:00
Paul Tarjan 55acd87832 fix namespace assert
this need to check the short form not the original.
sosorry
2013-06-04 17:53:38 -07:00
Mike Magruder 5299e5ba0d Basic stepping in generators
Add reasonable behavior for stepping within continuations (generators). Stepping over a yield now does what one would expect. When the generator is driven from a C++ extension like ASIO, the next logical execution point is after the yield statement, and that's where we'll stop now. When driven from PHP, say in a loop calling send(), the next execution point is in fact the call site of send(), so we go there. Stepping off the end of the generator function, goes to the caller of send(), or the caller of the C++ extension. Stepping _out_ of a generator driven by a C++ extension ensures that we go to the caller and not back into the generator again. The logic for both cases is exactly the same. The difference comes from the fact that we don't actually debug C++ extensions.

This also fixes a long-standing problem where breakpoints would interfere with control flow cmds on the same source line. This caused funny behavior, like taking multiple steps to get off of a breakpoint.
2013-06-04 17:53:37 -07:00
Jordan DeLong 3866a8b966 Verifier: treat Throw and Unwind as terminating a block
isCF() was returning false for instructions without jump
targets.
2013-06-04 17:53:37 -07:00
Herman Venter a73eaaabd9 Do not persist the EnableDebuggerColor config option into the hphpd.hdf file
The ~/hphpd.hdf file provides the ability to customize (or turn off) colorization in hphpd as a user preference. The EnableDebuggerColor option turns of colorization for a single run only and should not persist into hphpd.hdf.
2013-06-04 17:53:37 -07:00
Paul Tarjan d95fd236d2 flakey tests
Stop using the same filename!
2013-06-04 17:53:37 -07:00
Paul Tarjan b369aa91bc compile with -Wunused-but-set-variable
Our open-source build compiles with these warnings, so they cause spew when building from github. And I think they are good to catch programmer error.
2013-06-04 17:53:37 -07:00
Paul Tarjan 9d085274c1 add individual CLA
The other one was for corporations. We should be using this one most often.
2013-06-04 17:53:37 -07:00
mwilliams 0007231452 Fix spew from hphp when it tries to constant-fold php-builtins
trigger_error bypasses the usual error handling, so
explicitly test for throwAllErrors.
2013-06-04 17:53:37 -07:00
Sara Golemon fb60327fb0 Update Folly 2013-06-04 17:53:37 -07:00
Adam Simpkins f40b14aa63 Always require the register_libevent_server() function
Update CMakeLists.txt to force the linker to always pull in the
register_libevent_server(), even if none of the source files reference
it.  This is needed to register the "libevent" server type on startup.
2013-06-04 17:30:03 -07:00
Paul Tarjan ff25486f9f Revert cache size changes
This will need some love first
2013-06-04 17:11:55 -07:00
Paul Tarjan 4ee7a582d6 make caches exact multiples of 2 megs
This is the page size and will cause weird segfaults if they aren't multiples.
2013-06-04 17:54:46 -06:00
Paul Tarjan ab4b5ce72a Update .travis.yml
Now with the smaller cache sizes, can we support 4 threads?
2013-06-04 17:21:45 -06:00
Paul Tarjan 37edc8b56e Update .travis.yml
test/slow/locale/176.php depends on this locale being present
2013-06-04 17:19:34 -06:00
Paul Tarjan 628487943f a bit more? 2013-06-04 15:27:50 -07:00
Paul Tarjan 1646097b50 try less RAM 2013-06-04 14:19:34 -07:00
Paul Tarjan fcfc758672 try slow 2013-06-04 13:38:37 -07:00
Jan Oravec 8834f9211b Embed ContReceive into UnpackCont
Hoist ContReceive to the beginning of continuation body and make it part
of UnpackCont. This is a preparation for passing m_received thru the
stack.
2013-06-03 23:54:41 -07:00
Alexandru Suhan 93edca4397 Smaller c_Continuation
Save 16 bytes in c_Continuation by moving running and done flags to o_subclassData and making labels 2-byte.
2013-06-03 23:54:41 -07:00
Adam Simpkins be42cb5fdc add a ServerFactory class
This refactors the Server creation code, to make it easier to create new
Server implementations in the future, and to separate the LibEventServer
code from the main hphp_runtime library.

This defines a new ServerFactory interface, and a ServerFactoryRegistry
which maintains a mapping of server type strings to ServerFactory
objects.  The HttpServer code now uses a ServerFactory to create the
m_pageServer, rather than directly creating a LibEventServer object.
2013-06-03 23:54:40 -07:00
Adam Simpkins 31d042061c move warmup thread functionality out of LibEventServer
This moves the warmup thread logic from LibEventServer to a new
WarmupRequestHandler class.  This will allow the logic to work with any
server implementation, since it isn't really specific to LibEventServer.
(Eventually it would perhaps be nice to decouple the worker thread
behavior from the server I/O implementation entirely.)
2013-06-03 23:54:40 -07:00
Adam Simpkins b69fe9baf1 move addTakeoverListener() to the Server API
Make addTakeoverListener() part of the top-level server API, instead of
being specific to LibEventServerWithTakeover.  Servers that don't
support socket takeover simply ignore this call.

This will allow future server implementations to support socket
takeover.  This also allows us to start making the server creation logic
in HttpServer a bit more generic, since the code can always call
addTakeoverListener() without having to know if it really has a
LibEventServerWithTakeover or some other type of server.
2013-06-03 23:54:40 -07:00
Adam Simpkins e7a5f77b35 replace Server::shouldHandle() with a std::function
Change the Server API so that users don't have to subclass it in order
to override shouldHandle().  Now users can specify a custom
std::function for checking allowed URLs.

This will make it easier to provide alternative Server implementations.
Previously InternalPageServerImpl had to subclass LibEventServer in
order to override shouldHandle().  This tied the code to LibEventServer,
so that it could not be easily changed to an alternative implementation.

It seems like this URL checking functionality should perhaps be moved
into the RequestHandler.  However, for now this is a simpler change.
2013-06-03 23:54:39 -07:00
Adam Simpkins ee27bfa147 refactor RequestHandler behavior
This refactors the RequestHandler code, to decouple RequestHandler
behavior from the Server implementation.  The goal is to make it easier
to define additional Server implementations, in addition to just
LibEventServer.

This adds a RequestHandlerFactory function, rather than using a pure
virtual method of the Server class.  With the old model, you had to
subclass each server implementation separately for each RequestHandler
type you wanted to use, resulting in NxM classes if you have N server
types and M request handler types.

This also changes the behavior of the RequestHandler class somewhat:
the code now only creates a single RequestHandler per thread, and uses
that object for all request in that thread.  Previously the
LibEventServer code would attempt to create a new RequestHandler object
for each request if supportReset() returned true.  This was used by
RPCRequestHandler.  Now the RPCRequestHandler instead just resets itself
automatically when necessary, without requiring external help from
LibEventServer.

contbuild test runs failed due to git server issues.
2013-06-03 23:54:39 -07:00
Jan Oravec e6bd76e3fd Kill m_should_throw
Do not check for m_should_throw from ContReceive. Add a label used by
ContRaise pointing to Throw emitted by the Yield instead.
2013-06-03 23:54:39 -07:00
Drew Paroski a41fb387a7 Fix parsing for generic constraints with the "as" keyword
For generic constraints, the grammar (incorrectly) did not allow for
generic types on the right hand side of the "as" keyword. This diff fixes
the grammar appropriately.
2013-06-03 23:54:38 -07:00
Paul Tarjan 9519cefd00 fix parser tests
I was quite stupid in my rewrite and totally broke this. Wow, it runs fast!

I had to switch to `HHVM_BIN` as the env var, since it seems we force `HHVM` to 1 all the time...
2013-06-03 23:54:38 -07:00
bsimmers 8987de3e84 Remove immstack.cpp
It's dead but I missed it in my previous diff
2013-06-03 23:54:37 -07:00
Paul Tarjan ca5b712ddd resolve potentially global namespaced functions
When we see `define('Foo', 'Bar')` in a namespace, we don't know if it is talking about the global define function or the a local namespace one. What should we do? Does marking constants Dynamic that aren't actually dynamic break anything? Without this, HPHP creates a creates a CodeError.js

Closes #771
2013-06-03 23:54:37 -07:00
mwilliams 013c18b1f8 Fixup lots of include paths
This fixes most remaining paths to be relative to the git root.
2013-06-03 23:54:37 -07:00
Sean Cannella 722c0bd2d0 overrides need to come after defaults in test/run
- reverse order of default and test args so test args override
2013-06-03 23:54:36 -07:00
mwilliams f5387771e6 Fix overloading issues with Variant::nullInit
After Variant::Variant(NullInit) was made explicit, passing
Variant::nullInit to a function expecting CVarRef, or Variant
would actually call Variant(0), with ensuing hilarity.

Make NullInit an enum class to prevent such issues.
2013-06-03 23:54:36 -07:00
Mike Magruder cdc4a8eee5 Remove generated generator function name from test
Get the generated function names out of the test output.
2013-06-03 23:54:36 -07:00
Owen Yamauchi 739450013f Move runtime/eval/debugger to runtime/debugger
runtime/eval is now gone. Woooo

This is just a git mv + `codemod runtime/eval/debugger runtime/debugger`
2013-06-03 23:54:35 -07:00
Mike Magruder 609abd866f Fix step out bugs (also effects Next)
We had a lot of odd behavior with both Next and Out. Previously the debugger would interpret the world until it saw that it was no longer on a specific line, or at a specific stack depth. I changed it recently to let the program run normally, and use an internal breakpoint to control step outs. Next's become like a step out temporarily when you descend into a function and need to get back out to the original line, so some bugs with out showed as bugs with Next, too.

Specifically, any time more PHP code was executed as a "side-effect" of a non-fcall instruction, step out would get lost. In these cases the stack trace gives us the offset of the instruction causing the PHP to run, not the instruction that control will return to as is the case with a Fcall. A breakpoint set there would get missed. This changes the step out logic to recognize such cases (via the fact that a nested VM state was pushed to execute the code) and step out more intelligently. We look at the instruction in question, and determine where execution may go, which might be multiple places. I also made a small change to ensure that we don't stop in generated functions when stepping out, which cleans up the iterator experience quite a bit, and sets us up for proper generator stepping, which will come next.
2013-06-03 23:54:35 -07:00
Owen Yamauchi 9494a366b5 Move runtime/eval/runtime/file_repository.* to runtime/base
runtime/eval is a relic of a bygone era. As long as we're cleaning up
our directory structure, let's move FileRepository (the only remaining
thing in runtime/eval/runtime) to where it makes sense.

runtime/eval still contains the debugger, which would probably make more
sense as runtime/debugger, but I don't want to throw a wrench in the
works for @mikemag and @hermanv unnecessarily.
2013-06-03 23:54:34 -07:00
Paul Tarjan 8eaa77f319 rejigger systemlib
I've always been a bit sad about having all classes in the same file to govern inclusion order. And the filenames didn't match the class names.

Instead, lets not rely on whatever order `find` returns, and instead hard-code the ordering of the system lib. I grouped the files by what extension they came from.
2013-06-03 23:54:26 -07:00
mwilliams 6b50ac0477 Fix PACKED_TV test failures
In the PACKED_TV build, two tests were failing due to treating
the type as a 32 bit field.
2013-06-03 12:44:07 -07:00
Tim Starling 998951619f update copyright date
We did not intend to imply our copyrights last forever

Closes #759
2013-06-03 12:43:56 -07:00
Paul Tarjan f3abe784d4 make all tests the default
I think this is easier to explain
2013-06-03 12:21:16 -07:00
mwilliams 98de876586 Fix uses of FBMAKE_BIN_ROOT
Its supposed to be a relative path from the fbcode dir,
but various tools assumed it was an absolute path.

In particular, test/run failed if it was set, but was
not an absolute path, and tools/run_test_binary.sh failed
if it was set and was an absolute path.
2013-06-03 10:55:24 -07:00
Paul Tarjan 7f4e3c39d6 implement SplFileObject
This diff started off with trying to actually build `SplFileObject` since it was just stubbed out. But then I had to implement everything that extended from it since C++ classes can't extend PHP classes. And then it ballooend into what you see here. I actually think this is better in the long run, so that's why I kept going down this road.

The only thing that doesn't work in pure PHP is `sscanf`. @mwilliams has a fix for that. We need variable args by reference.

I implemented `RecursiveIteratorIterator` in a similar way to our C++ code instead of copying Zend. It translated to PHP a bit nicer. We still don't support the `RecursiveTreeIterator`, but I havn't come accross a need for that yet. I changed the implementation to actually use the `getChildren()` methods instead of peaking inside the `RecursiveDirectoryIterator`.
2013-06-03 10:55:24 -07:00
Paul Tarjan ae636a0a85 stop warnings
##hphp_471## isn't building. Lets try this. (It is also correct I think)
2013-06-03 10:55:05 -07:00
Jan Oravec 58c030adc8 Fix race condition in ExternalThreadEvents
A race condition can occur when the processing thread tries to notify
condition that is not yet waited upon. This can happen during the short
window in the web request thread between transitioning to the WAITING
state and calling condition.wait().

Fix this by locking mutex right before notifying the condition. If the
web request thread is in WAITING state, it is guaranteed to hold the
mutex or wait for condition variable. If the processing thread was able
to transition away from the WAITING state and grabbed the lock, the web
request thread must be waiting on condition variable, so it is safe to
notify it.

Thanks @andrii for tracking the bug down to ExternalThreadEvents and
providing a workaround (grabbing the mutex few lines up than this diff).
2013-06-03 10:55:04 -07:00
Jordan DeLong afa6d733c1 Some optimizations for LdClsCns
Change LdClsCns to side exit when the type is uninitialized.
On the exit path, do a LookupClsCns and ReqBindJmp for the next srckey
so forward progress is still made.  Add a predictionopts case for the
common case of a LdClsCns; CheckInit being followed again by a
CheckType---in this case, hoist all the checks into LdClsCns.
2013-06-03 10:55:04 -07:00
Jordan DeLong f008eafffe Move SrcKey out of translator.h and Transl:: @override-unit-failures
I was going to #include translator.h in a header I had for
talking to the region selector thing and decided to just get this over
with instead.  (It shouldn't need to #include that.)  Found a few
other unused things to remove while at it.
2013-06-03 10:55:04 -07:00
Jordan DeLong d3f443efdf Remove unused member function 2013-06-03 10:55:04 -07:00
Jordan DeLong 05c607e0a7 Print objects of specific classes better in JIT::Type::toString @override-unit-failures
Right now it returns "{}".
2013-06-03 10:55:03 -07:00
Jordan DeLong 2e08484a68 Don't use CSEHash::filter in TraceBuilder::reoptimize @override-unit-failures
Since hitting in the CSE hash is probably more rare, just
wait to check that the cse-candidate dominates the instruction in the
target block until it is looked up.  For now doesn't remove the
1000-block limit on reoptimize (we'll do this soon when we have time
to test it).
2013-06-03 10:55:03 -07:00
Edwin Smith 94a9ad531b A few more accessors losing their get prefixes
More verbose accessors becoming less verbosely named.
2013-06-03 10:55:03 -07:00
mwilliams 3f33747091 Implement array_filter and array_map in php
There's a lot less overhead calling the callbacks from php,
and now we have bytecode support for "withref" operations,
they're much faster.
2013-06-03 10:55:03 -07:00
mwilliams b1eedaa49f Change semantics of DecodeCufIter
Previously it returned a bool to say whether or not it had
succeeded, but always initialized the iter. The other iterators
branch on failure.

This adds the branch target which brings it closer to the other
iterators, and avoids the need to do a (pointless) CIterFree on
the failure path just to keep the validator happy.

I've also added a translation for it.
2013-06-03 10:54:44 -07:00
Owen Yamauchi dfae726e62 Fix unsatisfied order dependency in systemlib
SplPriorityQueue depends on SplHeap. Make sure SplHeap appears first.
2013-06-03 10:54:44 -07:00
bsimmers cf197fee81 Collapse runtime/vm/translator's contents into runtime/vm/jit
Facebook: ~bsimmers/bin/move-vm-files.sh
2013-06-03 10:54:43 -07:00
aravind a686bd4ca1 Remove BPass* instructions 2013-06-03 10:54:40 -07:00
bsimmers 991c1e3bdb Rip out preconsts
This was barely a demonstrable win in sandbox mode when I first wrote
it and it's not even used in hhir. It's probably been bitrotting and is causing
crashes for some people. Time to say goodbye.
2013-06-03 10:54:40 -07:00
Paul Tarjan bec594ceda disabled tests that only test underlying library
I'd rather not do this, but can't think of another good way. These 4 tests are failing on our opensource build since the image librarys are different there. The files they made end up looking the same but the bytes are different.

I just recently re-enabled these tests as they were a big comment (which I assumed was by accident) in the PHP-in-C++ version. (I'm using that to justify that we weren't covered before).
2013-06-03 10:54:40 -07:00
Herman Venter fd977f7091 Expose a config file option for turning of colorization in hphpd output.
Expected test output for hphpd command line tests is difficult to read when colorization is present. Although there was an internal switch to turn off colorization (for the benefit of API clients), there was no command line option and no config file option to turn off colorization. This diff adds such an option and also fixes a few places where colorization was added regardless of the value of the internal switch.
2013-06-03 10:54:40 -07:00
Drew Paroski 9e1e4e0573 Revert "Rename closures and generators"
This reverts commit f9e1a492285d27021ba50c49049823e7516edb6a.
2013-06-03 10:54:39 -07:00
bsimmers 687164d21b Kill more of tx64
I started by just killing a few unused flags from
NormalizedInstruction and then deleted things that were even slightly
related (and things that depended on them, etc...).
2013-06-03 10:54:39 -07:00
Jordan DeLong 9adc532349 Fix a type bug in BindS and BindG
They should load as a V not a C.
2013-06-03 10:54:39 -07:00
bsimmers 9272f42a88 Fix a lint error 2013-06-03 10:54:38 -07:00
mwilliams 12b768a06a Make exif parser more robust
Currently, as soon as it finds a bad field, it gives up.
Some android devices consistently create a bad field (that
we dont care about) right before fields that we do care about
(the orientation, in particular).

Most exif parsers just move on to the next field in this case;
this changes ours to do the same.
2013-06-03 10:54:38 -07:00
Bert Maher 8e34cbdf15 Allow CSE of ArrayGet by converting to IncRef
ArrayGet has fairly minimal side-effects: IncRef of its
result, and raising a warning if the element is undefined.  To CSE
ArrayGet, replace it with an IncRef of its destination.  Raising
multiple warnings for repeated accesses doesn't seem to have much
value, so just ignore them.
2013-06-03 10:54:38 -07:00
mwilliams 785b07cc42 Fix some hhbc verifier bugs
With these changes, we can run

  HHVM_ALWAYS_VERIFY=1 HHVM_VERIFY_VERBOSE=1 hhvm

without crashing.
2013-06-03 10:54:38 -07:00
Edwin Smith 8e78ddd0b1 More get-ectomy in IR code.
This is about all I plan on doing for now.  Simple accessors
lost their 'get' prefix.  Complicated functions are either still
called getWhatever, or got renamed (genWhatever, makeWhatever).
2013-06-03 10:54:37 -07:00
Guilherme Ottoni 97e2eac6a7 Relax more guards
This diff significantly generalizes guard relaxation and adds support
for more bytecode instructions.  Before, only CGetL, SetL, RetC, and
RetV were able to relax their inputs, and only in limited ways,
e.g. if their outputs were not used or only used in specific ways.
The new approach follows how the input types flow into the output
types, thus allowing dependencies to be relaxed even if they feed a
chain of values through the tracelet.

This diff also add support for relaxing inputs for the following
bytecode instructions:
  - Pop*
  - FCall
  - FCallArray
  - AddElemC
  - ArrayIdx
  - SetS
  - SetG
  - ContPack
  - ContRetC
  - ContHandle

The spill area was also increased (from 16 to 32 cells) since relaxed
dependencies increase register pressure -- relaxed types are not
immediates that can be burned in and need to reside in registers
instead.
2013-06-03 10:54:37 -07:00
Herman Venter 5a9d8751af Move the debugger command line test out of the C++ debugger test harness and use the standard harness.
Added a tweak to test/run to make it look for $test.in and, if there is one, to add <$test.in to the command line for running the test. Together with $file.opts and a config.hdf, this makes it possible to fire up a command line debugger for php, feed it with commands, obtain its output and check it against expected output.
2013-06-03 10:54:37 -07:00
Jan Oravec 817d94ebe1 Change iter_value() to return TypedValue*
Make internal iterator API return a TypedValue* instead of Variant. This
makes it possible to use the same API to update the value in-place
(except for Set, which returns const TypedValue*) and provide optimized
iterator that avoids unnecessary ref counts.
2013-06-03 10:54:36 -07:00
Sara Golemon 25e430f996 Update md5_file() and sha1_file() to use hash's streaming digest
For large files, the old approach would potentially
allocate ridiculous amounts of extra memory.  Let's not do that.
2013-06-03 10:54:36 -07:00
Paul Tarjan baceec1cb7 make test runner better
Some suggestions after talking to @bsimmers

* Print failing tests and diffs as it runs
* Remove the list of failed tests at the end (since they print as you go) and instead give a one-liner to re-run failed tests.
* Use moar colorz!
2013-06-03 10:54:36 -07:00
Paul Tarjan ae4d1a0def fix callble typehint in interp mode
Somehow the JIT doesn't hit this codepath, but with interp mode the param is a string, but we think `callable` means an object of type callable.

I hate to hadd another top-level if statement to every call. Would a switch statement on the type be better?
2013-06-03 10:54:36 -07:00
Paul Tarjan 0204047cce use 2 threads
1 took way too long...
2013-05-31 13:19:52 -07:00
Paul Tarjan df5730104c single-thread the tests
I'm worried there is memory pressures. Better safe than sorry for now.
2013-05-31 13:31:24 -06:00
Paul Tarjan 68e6cf3ba8 use --arg
Drew hasn't fixed argument parsing yet
2013-05-31 13:11:53 -06:00
Paul Tarjan 56964b4ea7 only use 8 threads
Travis was running out of memory. I also use 8 for compiling.
2013-05-31 12:52:39 -06:00
Paul Tarjan 8a29e9e6c8 Run all tests together
That way you don't depend on the previous suite passing
2013-05-31 12:37:14 -06:00
Paul Tarjan 40093d5bda Add zend tests to travis
With the updated systemlib they should pass
2013-05-31 12:25:49 -06:00
Sara Golemon b759586f06 Merge branch 'master' of https://github.com/facebook/hiphop-php 2013-05-31 11:20:33 -07:00
Sara Golemon 6bd13308da Update systemlib from source files.
Failed to generated this during the last push.
2013-05-31 11:19:51 -07:00
Paul Tarjan 0eef7b5935 Run quick tests in travis
The slow ones seems to abort halfway through, and a few zend ones aren't passing right now. :(
2013-05-31 12:12:52 -06:00
mwilliams 716a01c85e Kill lots of tx64
Its dead
2013-05-30 17:39:25 -07:00
bsimmers 8733cdc4f3 Run hhir exit traces during unwinding; don't spillstack before most helpers
Most of the SpillStacks we do are just to keep the in-memory VM stack
clean in case a helper call throws an exception. Many of these exceptions are
vanishingly rare, so let's stop making the fast path slower for them. This diff
adds support for catch traces, which are just like normal exit traces with one
major exception: they're never jumped to from translated code. If we're
unwinding a TC frame and discover that the current rip has a catch trace
registered, the unwinder will execute it before resuming unwinding.

The unwinder parts were fairly straightfoward, then I ran into a bunch of
issues with SetM. The SetElem instruction sometimes consumes a reference to one
of its inputs, which is bad news for our optimizations. To make everything work
again, I changed SetElem to throw an exception in cases where it would've
previously decreffed the value input. This is a special exception that the new
unwinding code recognizes. When one of these is caught, the catch trace
executed for that TC frame will finish up the vector instruction and push the
value provided by the exception on the stack. This allows us to optimize most
traces under the assumption that SetM's output is the same as its input,
letting the catch trace clean things up if the helper decides that's not the
case and throws.

There is one common case where SetM's output isn't the same as its input:
setting an offset in a string base returns a new String. Luckily, we can detect
most of these at compile time so SetElem returns a new StringData* when the
base is known to be a string. If the base might be a string, SetElem will
return nullptr if the base wasn't a string, and a StringData* if it was. We
test the output in these cases and side exit if the return value of SetElem is
non-null (I have yet to see this side exit happen outside of artificially
created test cases).

Once I got things working in the vector translator, I went through every other
call to spillStack and exceptionBarrier, replacing them with catch traces as
appropriate.
2013-05-30 17:39:25 -07:00
Paul Tarjan 677900f05d Use a pretty ascii art boat for all tests passed.
From http://www.chris.com/ASCII/index.php?art=transportation/nautical
2013-05-30 17:39:24 -07:00
Paul Tarjan ebf437281c Don't escape exception error messages in command line mode
The main impetuous was "\" is the namespace character, so I want namespace errors to not have double backslashes everywhere.

After finding that, it turned out we were escaping all exceptions in the command line, which is wrong. We only want the escaping when we are in server mode (emulating apache)

I basically pushed what we were doing in ##error_log## down to ##Logger::Log##.
2013-05-30 17:39:24 -07:00
Paul Tarjan 4022b5240a add SplPriorityQueue
Tons of copypasta from `SplHeap`. I'd love a better way...
2013-05-30 17:39:24 -07:00
Owen Yamauchi 494adcb2f4 Clean up HPHP flags a little bit
Some of this is trivial stuff -- flags that aren't even referenced except to read
them from the command line. I removed a few more that weren't used in
any meaningful way.

I figure we could also stand to remove --nofork, since "freeing up
memory for g++" isn't a concern anymore, but I figured it might still be
useful somehow.
2013-05-30 17:39:23 -07:00
Edwin Smith 0b599e48fa Remove old memlim code.
This has been turned off for about a month and is hopelessly
bitrotted.
2013-05-30 17:39:23 -07:00
Jan Oravec 57f1460cc7 Use virtual method return type covariance in clone()
Let clone() return pointer to the actual type instead of returning
pointer to generic ObjectData. Avoids unnecessary static casts.
2013-05-30 17:39:23 -07:00
Herman Venter 0cdf54a970 Insert new lines between object properties when serializing with DebuggerDump
DebuggerDump did not separate object properties with new lines. Now that it is used for cases with PrintR was previously used, the new behavior should be to insert the new lines.
2013-05-30 17:39:22 -07:00
Owen Yamauchi fee428f6fb Some compatibility changes for more recent versions of boost
- boost::shared_ptr now has "explicit operator bool", which means we
  can't "return <a shared ptr>" from a function with return type bool.

- Our use of shared_ptr<T[]> in debugger_client.h was screwed.
  Unfortunately it's not straightforward to make it a unique_ptr as per
  our discussion; there are other objects that call setLiveLists, and
  it's not clear to me that this is a total transfer of ownership. I'm
  just fixing the immediate problem using shared_array. (Also made the
  typedef less confusing, hopefully.)

- Our specialization of graph_traits<G> for ControlFlowGraph didn't
  define the null_vertex member function. This didn't matter in older
  versions of boost because they didn't use it internally, but now they
  do (the call to depth_first_search in control_flow.cpp was failing to
  compile).
2013-05-30 17:39:22 -07:00
Edwin Smith 92a4705514 Move the large-ish collections functions out of line.
These seem on the big side to make them inline, and the conversion
from string literals to StaticString is cleaner if the ones that
use string literals are not in headers.
2013-05-30 17:39:22 -07:00
Paul Tarjan d8d1e7f840 add simplexml_import_dom
This is needed for Symphony.

I copied the zend implementation and then cargocult programmed the rest from the other 2 functions in the file.

Closes #789
2013-05-30 17:39:21 -07:00
Paul Tarjan b4d4e630c3 rewrite test running in php and cleanup test output
I started cleaning up the perl script and then realized that it wasn't buying us much at all. So I changed the ##test/run## script to just do the executing of the ##hhvm## directly and printing the output.

While I was in there, I also made the ##verify_to_json.php## redundant by allowing different output formats, one of which fbmake can consume.

A good run looks like:

    $ test/run test/slow/array
    Running 68 tests in 20 threads
    ....................................................................
    All tests passed. Ship it!

and a bad run looks like:

  $ test/run test/zend/good/ext-bz2
  Running 5 tests in 5 threads
  ....F

  1 tests failed:
  test/zend/good/ext-bz2/002.php

  To run these by hand:
  hphp/hhvm/hhvm --config test/zend/config.hdf  -v Repo.Local.Mode=-- -v Repo.Central.Path=/data/users/ptarjan/other-git/fbcode/hphp/test/../../_bin/verify.hhbc -v Eval.Jit=true -v Eval.JitEnableRenameFunction=true -v Eval.EnableArgsInBacktraces=true --file test/zend/good/ext-bz2/002.php

I chose to not support the ##1..1## syntax since only 5 tests were using it.
2013-05-30 17:38:57 -07:00
mwilliams 78ca8ecbaa Add bytecodes to decode a function, and push an actrec for a decoded function
array_filter and friends only need to evaluate the callback once,
so add bytecodes to support that.

Depends on D817883
2013-05-30 17:33:05 -07:00
Edwin Smith 177f1add3e Make DefLabel optional at the front of a Block.
A DefLabel instruction with 0 destinations is a NOP, so make it
optional; only generate DefLabels when we need phi-parameters to
the block.
2013-05-30 17:33:04 -07:00
mwilliams c12714e2bb Add bytecodes for some "withRef" operations
Functions like array_filter and array_map need "withRef" semantics,
and while it can be simulated in php via copy-on-write, doing so
is very inefficient.

This adds

  SetWithRefLM
  SetWithRefRM
    - similar to SetM but binds the value if it was a reference. L reads a local, R reads a return value

  WIterInit
  WIterInitK
  WIterNext
  WIterNextK
    - essentially the same as the corresponding opcodes without W, but the value local is set by reference if the array element was a reference.
2013-05-30 17:33:04 -07:00
Guilherme Ottoni ec6ab13b15 Fix typos: MMX => XMM
I just noticed some stuff using MMX in their names where they should be XMM.
2013-05-30 17:33:03 -07:00
Herman Venter a9fa4568fe Always use DebuggerDump for printing values in hphpd client console.
The proximal purpose of this differential is to fix the debugger client so that it does not write raw strings to the console (with control characters doing their thing to the console and unprintable characters pretending not to exist). This change in behavior means that the serializer used to convert values to strings can no longer be instantiated with the PrintR option, as it has been in a subset of cases. (The reason being that print_r() must not change its behavior.)

Rather than introduce yet another serializer option, I decided to always make the debugger client serialize user visible values using the existing DebuggerDump option, which is already used in a number of such  cases and which has no other use. To make the overall change less painful for users, I preferred to change behavior of DebuggerDump to be more like PrintR in a number of cases, primarily the formatting of objects (where the current behavior is to make a JSON like string).

This does not impact the behavior of the debugger client API or the behavior of FBIDE, since these do their own thing directly with the DebuggerSerialization format and never see the result of the DebuggerDump format.
2013-05-30 17:33:03 -07:00
Sara Golemon 6927cf84e4 Objectify and clean up bootstrap programs.
Refactor a lot of idl.h/idl.cpp to be more generic and
make them easier for other bootstrap apps to build on.

This is a precursor for building infotabs/class_map generators
in cpp to remove the need for PHP during bootstrapping.

I'll also be git mving this to hphp/tools/bootstrap
in a follow-up move-only commit.
2013-05-30 17:33:03 -07:00
Sara Golemon c3193512d6 Pull DataType and related asserts/macros/inlines into separate header
Allows DataType to be referenced without having
to pull in the entire kitchen sink of hphp/runtime.

This will be used by the bootstrap process for creating
ext_hhvm, infotabs, constants, systemlib, and class_map.
2013-05-30 17:33:03 -07:00
Edwin Smith 8a8b27071f remove "get" from label, trace, block, hint, next, taken, extra
Makes the code less repetitive and easier to read
2013-05-30 17:33:02 -07:00
Jordan DeLong 0e7c8a33f2 Use an enum for SimpleFunctionCall::m_type instead of an int
It already had an enum, but wasn't using it.
2013-05-30 17:33:02 -07:00
mwilliams 71859e5566 Add support for .hhas files in systemlib
Will be needed for array_filter/array_map etc

This sets things up so that if we define a builtin in systemlib, we rename
the corresponding c++ builtin with the prefix __builtin_, so its still available
(in case the php builtin wants to delegate some edge cases, and to make
it easy to run comparisons between the php and c++ implementations).

Also did a little reorganization to get rid of Func::isPHPBuiltin,
and use an Attr to identify functions as builtins. C++ builtins can
still be identified by checking the Func::info() method. This is needed
to allow builtin methods defined in php (such as array_map) to lookup their
arguments in the correct context.
2013-05-30 17:33:02 -07:00
Edwin Smith 0fabe930f8 Rename s/get// for id, src, dst, srcs, dsts, numSrcs, numDsts
Dropping the "get" prefix makes the code more readable.
Also srcReg(), dstReg().
2013-05-30 17:33:01 -07:00
Wez Furlong 5301896d35 fixup environment inheritance
obsoletes D825704?  populate our env array from environ,
then overlay local changes that were made to m_envs.

I didn't make this conditional on CLI but could if that is desirable.

I didn't tackle the allocate-after-fork issue that @jdelong raised in D825704
2013-05-30 17:33:01 -07:00
Jordan DeLong 1c0a6c9082 Remove some linear searches; use a vector instead of a list for BlockList
Less malloc and less linear search.  Also renames sortCfg,
since @smith told me he didn't like that name very much.  This still
makes use of the postId() field on each Block, which maybe still has
us leaving some trash in the Block structure that should be on the
side.  (These functions can be changed to take indexes later instead
if we want to kill that.)
2013-05-30 17:33:01 -07:00
Jordan DeLong e405aa7bce Remove hoistGuardToLoad
This doesn't happen, and if it did it would be incorrect,
since it assumes a getTaken() implies a side exit which is no longer
true.  We may bring back something similar to this for LdClsCns but
it'll be easy to do it at that point (and a bunch of the instructions
in here aren't used as guards/checks anymore).
2013-05-30 17:33:00 -07:00
Jordan DeLong 03c652cb3c Minor tweak for better StateVector error messages
If you use StateVector<Block*,...> or similar on accident,
you get a bunch of junk.  Add a static_assert so there's at least a
reasonable error in there somewhere.
2013-05-30 17:33:00 -07:00
Misha Shneerson 2e72a2aba5 Do not suppress exceptions thrown by PHP transport
Currerntly, if TServiceRouterTransport::flush throws an exception,
this exception is swallowed non-chalantly by Thrift's extension layer.
This should not happen.
2013-05-30 17:33:00 -07:00
Jan Oravec 935011733c Make AsioExternalThreadEvent::abandon() not hit assertion error
Destructor of AsioExternalThreadEvent uses assert() to check whether the
state is legal. Introduction of abandon() mechanism makes it possible to
destroy the AsioExternalThreadEvent in the Waiting state and hit the
assertion error.

This diff solves the problem by introducing Abandoned state.
2013-05-30 17:33:00 -07:00
Paul Tarjan 992cd4efb6 add FilesystemIterator
This was inserted as a class inbetween RecursiveArrayIterator and DirectoryIterator. Sadly our RecursiveArrayIterator implementaiton is crazy and calls into C++ which can't call back up to `parent::method()`. I'll fix RecursiveArrayIterator in another diff.
2013-05-30 17:32:59 -07:00
Jordan DeLong 9638191f2a Remove emitInterpOneOrPunt
It just calls emitInterpOne now.
2013-05-30 17:32:59 -07:00
Jordan DeLong f93b15f67d Remove weird IncRef thing in emitBindL
The comment is correct that doing the IncRef first is
necessary in pseudo mains.  However, I can't see any disadvantage to
not doing it first outside of them---IncRef/DecRefNZ elision still
seems to kick in in all cases I can think of.
2013-05-30 17:32:59 -07:00
Jordan DeLong 85aa9442ac Fix AddNewElemC bugs in HHIR
emitAddNewElemC didn't properly implement the specified
behavior for this opcode.  It assumed topC(1) was always an non-static
array with refcount 1 or 0.  This changes to interp the case when it's
not an array, and make the helper support static arrays.  (If it
matters for perf, we should engineer the bytecode spec to require this
as well, since the point of this opcode is initializing array literals
that can't be done as static arrays.)  In practice I think this is
only working because it always comes after a NewArray with a capacity
hint != 1, which means it's a newly allocated non-static array.
Ignoring the capacity hint would've broken it.
2013-05-30 17:32:59 -07:00
Edwin Smith cd734dec99 Eliminate ArrayInit.set(litstr)
In runtime code, use StaticString for literals or String for computed
char strings.  In test code, I justed used String("literal") to keep
the conversion simpler.  I think tests are ultimately easier to maintain
without the StaticString treatment.
2013-05-30 17:32:58 -07:00
Drew Paroski 13c4c29555 Revert "[hhvm] proc_open should inherit g_context->m_envs"
This reverts commit 0a03e2fdd8cfa1c7dd0a1f9b836443a6464d69b2.
2013-05-30 17:32:58 -07:00
Jordan DeLong aef3e1ea9b Finish ir.specification entries for remaining instructions
I was looking over the instruction table to try to understand
what may need to happen to make it easier for a memelim mark 2 to
track memory effects (on object properties and other memory
locations), and I made the mistake of documenting StProp and StPropNT
(currently unused).  This led to finishing the remaining missing
entries...
2013-05-30 17:32:58 -07:00
Paul Tarjan c2ec1c97c9 sortof format slow tests
A poor man's formatter since I didn't like any of the other ones I found. The original C++ source sometimes put newlines and sometimes not.

Codemods:

    codemod '([;{}])([^\n])' '\1\n\2'
    codemod -m '\s*<\?php\s+' '<?php\n\n'
    codemod '\t' '  '

I hand-fixed all the failing tests
2013-05-30 17:32:57 -07:00
Paul Tarjan 8ea73f74b2 Update README.md
-m server runs from the current directory
2013-05-29 19:16:07 -06:00
Edwin Smith 89237f753a Keep track of predecessors all the time.
Use a struct wrapping from and to Block* pointers to represent
control flow edges, keeping a predecessor list up to date whenever
edges are updated.  This subsumes EdgeData, which was only used
to track jumps that pass values.
2013-05-28 10:30:28 -07:00
Dario Russi e93120812a Extend the type system of the JIT (Type class) to allow for specialized Class instead of just Type::Obj
Allow RuntimeType to specify a more specific Type (by adding a Class*) and transfer that Class* to Type. Extended API to allow discovering when a Type is a subclass of Type::Obj
2013-05-28 10:30:28 -07:00
mwilliams 23919b915f Fix crash/hang in Parser::newClosureName
The parser was updating a static std::map without a lock.
It looks like this is supposed to be local to a file anyway,
so add the map as a member of ParserBase.
2013-05-28 10:30:27 -07:00
Jordan DeLong 4f3c0c15b4 Fix a bug in codegen block order; add a step to choose the order
Codegen had a bug where if you emit a block in astubs that
has a getNext() which is also in astubs, it would omit the jump.
However, it might visit another block in a first, which is allowed to
put code in astubs.  Generally the block order was just defined by the
order that happened to be in the block list by the time we get there.

Change it to emit blocks in the RPO defined by sortCfg for now, after
partitioning them into groups for a and astubs.  This fixes the bug,
and at least makes codegen use a defined order.  We later will
probably want to see about whether we may be able to avoid more jumps
with smarter layout.
2013-05-28 10:30:27 -07:00
Jordan DeLong 42a6039125 Fix a bug with debug_backtrace during an unwind
The change to stop zeroing locals during RetC was too
aggressive---we stopped doing it during unwinding also.  When
unwinding, we need to zero locals and $this because another
destructing object may still run debug_backtrace, and we won't have
the *pc == OpRet{C,V} trick to tell us to ignore the junk.
2013-05-28 10:30:27 -07:00
Edwin Smith 76546fceb5 Don't use RAND_bytes() under valgrind.
The results are marked uninitialized and trigger spew.
2013-05-28 10:30:26 -07:00
Edwin Smith 1664473ecb Use uppercase for RuntimeOption static methods.
Main style for static functions is UpperCase.
2013-05-28 10:30:26 -07:00
Paul Tarjan 7930598d18 indent function docblocks 2013-05-28 10:30:26 -07:00
Jordan DeLong 2751922302 Fix a fallthrough bug in TranslatorX64::smash
If smash is told to generate a forward jump to a target less
than 7 bytes away, it nops out the intermediate region.  It's
currently impossible for this to cause any issues (as far as I know),
but technically there can be other instructions in there.  I hit this
by randomizing the layout of blocks in codegen---if you place a block
consisting of only a short backward jump immediately after the block
containing the main trace exit, and then a fallthrough-ish translation
occurs, smash will nop out the short-jump block.
2013-05-28 10:30:25 -07:00
Paul Tarjan bd9f92da9a add SplHeap, SplMaxHeap, and SplMinHeap
closes #505
2013-05-28 10:30:25 -07:00
Jordan DeLong 362f69b6fe Fix an issue in the register allocator
An optimization I'm working on sent the register allocator a
CFG that looked like this:

  M0
  | \
  |  M1
  M3 | \
  |  |  E4
  |  M8
  | /
  M2
  |
  M5

The RPO was 0 1 8 4 3 2 5.

It assert-fails here because it visited E4 before M3, and it appears
this would incorrectly mark everything as free.

This diff changes the register allocator to skip all non-main-trace
blocks during the first pass over the CFG.  Then each exit block is
visited.
2013-05-28 10:30:25 -07:00
Jordan DeLong d51ab6e272 Make LdClsCns not CSE-able
If you load the same class constant multiple times in a
tracelet, this will extend the lifetime of the LdClsCns, and reuse it
at sites past the CheckInit guard.  It can generate incorrect code if
the LdClsCns has a type more specialized than Cell (because if the
unlikely branch happens, later code will reuse the uninit value that
was loaded), and if the type is less specialized it keeps two GPRs
live longer than probably makes sense.
2013-05-28 10:30:24 -07:00
Jordan DeLong e3bdb5123f Remove edges when dce eliminates a whole block
If DCE eliminates a block that ends with a Jmp_, two things
can currently go wrong.  One is that linearscan will still inspect the
incoming edge to try to precolor jump destinations and fail an assert;
the other is that the type of the DefLabel destination may be too
relaxed.

This diff adds a new checkCfg invariant that all incoming edges to a
DefLabel are in the block list for the trace, and weakens the assert
in linearscan so things still work if DCE is turned off but a block
becomes unreachable.  Also changes dce's removeUnreachable to
reflowTypes if it removes an incoming edge.
2013-05-28 10:30:16 -07:00
Keith Adams 26e23732d3 Inline CreateCont's with arguments.
Well, this was a lot easier than expected. Don't give up inlining Cont creation just because it takes args.
2013-05-28 10:30:16 -07:00
Guilherme Ottoni 975afed427 Use r15 instead of r13 in generic return dec-refs
This avoids a bad interaction with LinearScan, which saves the return
value in r13 and r14 around GenericRetDecRefs.  Effectively, this diff
ends up saving a push, a pop, and some stack adjustment in
GenericRetDecRefs.
2013-05-28 10:30:15 -07:00
aravind 841670cd26 clean up SharedMap
This diff cleans up some of the mess in SharedMap. The existing way of accessing values in ShareMap is SharedMap -> SharedVariant -> ImmutableMap -> SharedVariant. This diff changes it so that the path is reduced to SharedMap -> ImmutableMap (with inlined SharedVariants).
(Likewise for VectorData)

The hashing scheme in ImmutableMap is left unchanged (chaining with ->next pointers, though we could change it to something similar to HphpArray).
2013-05-28 10:30:15 -07:00
Paul Tarjan 98589f6e87 support IteratorAggregateClass
someone added this class but didn't really hook it up. This was breaking Symfony.
2013-05-28 10:30:15 -07:00
Paul Tarjan e30d6e377b fix thrift for namespaces
Thrift doesn't autoload the class, it just does a ##lookupClass##. We need to normalize it so the lookup doesn't fail.

Closes #775
2013-05-28 10:30:14 -07:00
Paul Tarjan abb171eb41 allow (clone)->bar() and (<xhp>)->bar()
People have asked for ##(new Foo)->bar()##, ##(clone Foo)->bar## and ##(<xhp>)->toString()##.
2013-05-28 10:30:07 -07:00
Paul Tarjan 56172bc9fc Merge pull request #791 from ptarjan/unused_var
fix unused variables in third-party
2013-05-25 12:25:57 -07:00
Paul Tarjan 70fd03a5e7 fix unused variables in third-party 2013-05-25 12:09:41 -07:00
Paul Tarjan 39ccf09e05 change to webchat
github does't link irc:// links. Great.
2013-05-24 16:38:32 -06:00
Paul Tarjan 6c0ddfefca Added IRC and CLA pdf 2013-05-24 16:22:15 -06:00
Paul Tarjan ed171866b7 update docs 2013-05-24 10:10:58 -07:00
Andrei Alexandrescu 6d365df98f HphpArray compact layout
ArrayData gets on a diet, down to 32 bytes
devirtualized destructor call in HphpArray::release()
aggressively inlined constructors for ArrayData (do away with defaulted arguments)
eliminate a dead memset() for the hashtable in HphpArray(uint size, const TypedValue* values)
2013-05-24 10:10:17 -07:00
Herman Venter 5f75fbcf69 Restore syntax for specifying a breakpoint using only a line number.
The special case got over looked in the recent breakpoint parser rewrite. This change is a small point fix that restores this functionality while perturbing as little else as possible.
2013-05-24 09:48:43 -07:00
Jordan DeLong f50482c213 Increase level of getRegType traces
These are at too low of a level.  (Most per-pass logs in
hhir: are starting at "5" right now, mostly because it used to be the
same TRACE as printir.  I've been putting detailed per-pass info at 6
or 7.)
2013-05-24 09:48:43 -07:00
Paul Tarjan 39d6a7f26a add $name to ReflectionParameter
This is in the docs http://www.php.net/manual/en/class.reflectionparameter.php and is used by Symfony
2013-05-24 09:48:43 -07:00
Paul Tarjan 2d105535f3 fix idl/sysdoc.php
They changed their html to have an extra attribute in the `div`.
2013-05-24 09:48:42 -07:00
Paul Tarjan cef8fcc6e3 add ArrayObject
This is a pure PHP implementation of ArrayObject. It does't match the reference semantics of zend's implementation, but it is much easier to build this in pure PHP, so its a good first step. It is better to have it like this, than to not have it at all.
2013-05-24 09:48:22 -07:00
Paul Tarjan 0666f0df1e add CLA
If people don't want to use the CLA tool (if they don't have a FB account for example), then they can print this, sign it, and return it to us.
2013-05-24 09:48:21 -07:00
bill fumerola d9de1a83e3 re-order includes to satisfy lint header order rule
"The associated header file of .cpp files should be included before any other includes. (This helps catch missing header file dependencies in the .h)"
2013-05-24 09:48:21 -07:00
Herman Venter 58760b99ae Serialize partial class instances using correct class name
When hphpd does a print instruction for a value that is an object, the object is serialized in the proxy (server) and then deserialized in the client. If the client VM does not have the class loaded, then the deserializer creates an instance of __PHP_Incomplete_Class and adds the class name to it as the value of a property called __PHP_Incomplete_Class_Name. This then shows up in the textual output of the print command, which is a bit confusing to say the least. Ironically the printed output is obtained by serializing the object instance.

The basic design seems OK to me: The proxy should send the client the raw data and then leave it up to the client to figure out how to format it and what elide. And in this case, if the client is accessed via the API, the caller gets the raw data. So, it does not seem like a great idea to get the proxy to format objects so that the client just has to print the string as received from the client.

Instead, this diff changes the object serializer so that when the PrintR option (debug output format) is specified, incomplete class instances are serialized with the class name obtained from the value of the __PHP_Incomplete_Class_Name (if present) and the property itself is elided from the output.
2013-05-23 21:03:07 -07:00
mwilliams bec724926c Fix crash in hphp
The AnalysisResult for systemlib.php was allowed to go out of
scope, taking the FileScope with it, causing us to crash when
trying to flatten systemlib traits.
2013-05-23 21:03:06 -07:00
Paul Tarjan d4f57cbe3e add dom_import_simplexml
Needed for Symphony. We are labelling the dom extension as unsupported, is that still correct @sgolemon?

The iffiest part of the diff is new-ing up the ##c_DOMDocument##. Is that right?
2013-05-23 21:03:06 -07:00
Paul Tarjan c02df18f78 don't show Closure in get_declared_classes()
This was the fastest thing I could think of. Would string searching the name be better?

No user class can extend from Closure, so we're ok on that front.
2013-05-23 21:03:05 -07:00
Guilherme Ottoni 1cd5784ef6 Allocate XMM registers for some SSATmps requiring 2 64-bit regs
This diff allocates some SSATmps requiring 2 64-bit registers (value
and type) to a full XMM register, instead of allocating them to 2
64-bit GP registers.  If all def/uses of such SSATmp are simple
loads/stores from/to memory, then they're considered for allocation to
a full XMM register.

Since all XMM registers are caller-saved, an exception is made for
SSATmps crossing native calls.  In this case, if there are
callee-saved GP registers available, the SSATmp will be allocated to
them.

Also, I cleaned up code-gen for RetVal to use cgStore, and renamed the
IR instruction to StRetVal.
2013-05-23 21:03:05 -07:00
Guilherme Ottoni 7f19d85acc Kill translator-x64-vector.cpp, again
It ressurected somehow.
2013-05-23 21:03:05 -07:00
Alexandru Suhan eb5d2d1f00 CGetS output type prediction 2013-05-23 21:03:04 -07:00
Sean Cannella 685af88ccf fix file/class in backtraces involving traits
- non-repo mode: use fullName() instead of flawed logic in type constraint failures
- repo mode: save the original filename when flattening traits
2013-05-23 21:03:04 -07:00
Guilherme Ottoni a12865c040 Reserve r11 for code-gen's scratch fallback
This diff reserves r11 for the GP scratch register used by the
CodeGenerator (in case no better register is available). rScratch
(r10) is now reserved for the assembler, and was renamed to rAsm.
This avoids a class of subtle bugs where code-gen mixed uses of
rScratch with calls to the assembler that could also make use of this
register.  (Tx64 code still uses rScratch/rAsm for now.)

While here, also moved the reserved XMM scratch registers from the
assembler to CodeGenerator, since the assembler doesn't really use
them.  (The uses of these registers in Tx64 were renamed back to
xmm0/xmm1 as they were until recently.)
2013-05-23 21:03:04 -07:00
bill fumerola 771c423868 expose Vector->count() for use inside hphp 2013-05-23 21:03:03 -07:00
aravind 3ebcd53563 Revert "HphpArray" 2013-05-23 21:02:52 -07:00
Jordan DeLong ecc6a44af6 Hoist CheckType instructions above generic IncRef/LdMem @override-unit-failures
Because we normally find out about a type prediction at hhbc
bounderies, sometimes we generate type checks after we've already done
some generic operations on Cells.  This optimizes a specific pattern
of this that occurs in vector translations.  The code is set up as if
there is more than one since I have another case partially
implemented, but it currently hits issues in both linearscan and
codegen that need to be addressed first, so I split the diff for now.
2013-05-23 20:02:42 -07:00
Jordan DeLong 0b763991b6 New Block invariant
It's a little hard to reason about how lastMarker works in
codegen wrt blocks that don't have Marker.  In a optimization pass for
hoisting CheckType instructions I'm running into cases where I'd have
to track arbitrarily far backward in the main trace to find a Marker
that needs to go into the exit trace; it seemed simpler to just always
have a Marker in the front of each block.
2013-05-23 20:02:42 -07:00
mwilliams 4215e2b9d4 Fix defaults for preg ini settings
Use the RuntimeOptions, rather than hard-coding them
2013-05-23 20:02:41 -07:00
Guilherme Ottoni f3f3e0b48e Optimize ContSend, ContRaise, and ContNext for m_received being null
Make sure m_received is always null at ContSend, ContRaise,
and ContNext, and this information to generate better code for these
bytecode instructions.
2013-05-23 20:02:41 -07:00
Guilherme Ottoni d04d06c735 Increase spill area
Bump it from 8 to 16 Cells.
2013-05-23 20:02:41 -07:00
Andrei Alexandrescu fe73940a51 Refactor copyImpl() and nonSmartCopy()
I've done this refactoring without efficiency in mind - it's one of the steps toward more aggressive in-situ allocation. Yet to my surprise perflab rewarded this simple refactoring with a whopping decrease in I-TLB misses. I myself am wondering what has caused this. Anyhow let's run perflab once more and get this baby on the road.
2013-05-23 20:02:41 -07:00
Paul Tarjan 7059bc285f move test
StringBuffer is aparantly a facebook only thing
2013-05-23 20:02:40 -07:00
Paul Tarjan ceab90edaf is_dir should be false for false
This is breaking Symphony
2013-05-23 20:02:40 -07:00
aravind fec5acd7ec Treadmill for shared variants
Avoids atomic incRefs and decRefs. StringData no longer needs to
be sweepable for SharedVariants.
2013-05-23 20:02:40 -07:00
Chip Turner 65c4109224 Fix idl generation
Make idl generation work; properly use hphp/ paths, tweak some
out-dated names, etc.
2013-05-23 20:02:39 -07:00
Sean Cannella bdc1644753 gen_systemlib.sh should use passed-in files
gen_systemlib.sh currently takes a list of input files and then ignores them
2013-05-23 20:00:58 -07:00
aravind c51bb67028 Use AtomicHashArray for PCRE 2013-05-23 18:57:03 -07:00
Paul Tarjan c1705cb7c8 !bool != bool
I should have tested it :( While I was in there debugging I found some dead code

Closes #771
2013-05-23 18:56:55 -07:00
Owen Yamauchi dd43894685 Fix printing of ActRecInfo
If it's an AR for a constructor, the high-order bit is set, and it gets printed
as -2 billion. This is confusing; at first I thought it was a bug. Print it out
in a readable way.
2013-05-23 18:56:45 -07:00
Paul Tarjan 17c75f16d1 stop spew
The open source build complains about these: https://travis-ci.org/facebook/hiphop-php
2013-05-23 18:17:27 -07:00
Paul Tarjan 4f48bb7052 don't create an empty String
@mwilliams reminded me variables declarations actually make them.
2013-05-23 18:16:56 -07:00
bsimmers c4161ae787 Turn SrcRec
There's no compelling reason for this to be a fixed
constant. I also renamed EvalMaxTrans in an attempt to differentiate
it from the new option.
2013-05-23 17:08:18 -07:00
Sara Golemon fd2cc271b6 Update folly 2013-05-23 14:36:08 -07:00
bsimmers a9f529a91a Add TranslArgs and delete a bunch of tx64 code
I want to add a new argument to translateTracelet. Rather
than plumbing it through the many functions in the translation stack,
let's use an options struct. Dealing with the many bools we had flying
around controlling hhir was complicating things, so I removed
m_useHHIR and collapsed them all into an "interp" bool in
TranslArgs. I removed any code that was clearly unreachable from these
changes.
2013-05-21 11:17:37 -07:00
bsimmers 21b545f297 Nuke translator-x64-vector.cpp
Most of it was dead code. The few helpers that are still used
were moved to translator.cpp.
2013-05-21 11:17:36 -07:00
Andrei Alexandrescu 872d24b761 HphpArray
I've run a bunch of experiments on HphpArray speed and am still yet to have a major breakthrough. However, there are a few clear small winners that I'm submitting with this diff. CPU instructions, CPU loads, and CPU stores are all as green as the Eternal Hunting Grounds. Speed is drowned in noise but I sususpect will be measurable on these changes combined.
2013-05-21 11:17:36 -07:00
Drew Paroski 110f05277c Fix hphpd to not raise a notice when no file is given at the command line
"hhvm -m debug" without specifying a file should work without raising
notices. hphp_invoke_simple() and friends used to (incorrectly) tolerate
using an empty string for the file name, and hphpd was relying on this.

This diff fixes hphpd to not call hphp_invoke_simple() when no file was
given at the command line.
2013-05-21 11:17:36 -07:00
Paul Tarjan 9006ed7c1b idx is NOT a builtin
@seanc This is the second time... Third time we should figure out a solution
2013-05-21 11:17:35 -07:00
Sean Cannella 05a8a8d7ca Rewrite idx in PHP using IR instruction for hot path
- Do the actual work of implementing idx() in PHP
- Remove the old C++ builtin (which needs to be done at the same time)
- Remove OSS test dependencies on idx()
2013-05-21 11:17:35 -07:00
Erling Ellingsen dcf471996e Fix shapes
The keys were dropped.
2013-05-21 11:17:35 -07:00
Guilherme Ottoni d5657a46cf Fix propagation of predicted function-return types
Tx64 had an optimization in planPop() to avoid dec-refing a function
return value that's predicted by the front-end to be of a
non-ref-counted type.  This optimization was clearing the
outputPredicted flag in the NormalizedInstruction, thus preventing
HHIR from getting those predictions. So, I got rid of the optimization
in Tx64 to allow HHIR to get those predictions.
2013-05-21 11:17:34 -07:00
Mike Magruder 35e171458f Add client- and server-side logging to the debugger
Log details about debugger usage from both client and server side. Added a new runtime option to control whether the logging is used or not. There's a base class for a usage logger defined and used under runtime/eval/debugger.
2013-05-21 11:17:34 -07:00
Paul Tarjan c798a717b8 change version string
Now that we have all the 5.4 features, should we bump the version up? I wanted to pick the most recent version number, but we aren't really comparable since we aren't tracking the bugfixes. We might have them, we might not. I think we should just be the highest version of 5.4 so that all software tries to run us. Then we should expose our own version number incase software really needs some fixes from our tree.
2013-05-21 11:17:33 -07:00
Jordan DeLong f9c18fafd6 Rename jumpsopts to jumpopts 2013-05-21 11:17:33 -07:00
Paul Tarjan a9f7fee483 kill tryLockWait
There is no calls to `tryLockWait` in the codebase, and OSX doesn't have the underlying function, so why do we have it? It was added in D299757 with no callers.
2013-05-21 11:17:33 -07:00
Paul Tarjan 4d2e8af379 kill SpinLock
It is unused (and not implemented on OSX) so killing it seems good. It was introduced in rFBCODEe991769c74e876f345e2cd92edf1d970801e884b with no users.
2013-05-21 11:17:32 -07:00
Jordan DeLong c14f38d855 Mark all stack values available in an inlined callee
For DecRef -> DecRefNZ transitions.  Any value on the stack
at the callsite must outlive the callee.
2013-05-21 11:17:32 -07:00
Daniel Sloof 33817be827 change segment name for osx
OSX requires a comma after segment name. The segment name must also not be longer than 16 characters.

Pull Request: https://github.com/facebook/hiphop-php/pull/781
2013-05-21 11:16:51 -07:00
Paul Tarjan 6ef9d37225 fix builtin extension tests
In D804289 I scrwed up and needed a ##/g## in my script...
2013-05-21 11:12:06 -07:00
Paul Tarjan b2de6fb9da fix segfault for wikimedia
If you call a static method on a instance, we decRef the object before running the method. If that is the last reference to the object, then its destructor will be called right in the middle of setting up the ActRec for the static method. Currently, the top of the stack will be off by 2 Cells because we have already popped off one Cell (the object) and an ActRec takes up 3 Cells.

Instead, we have to have the top of the stack to be after the ActRec that we are building for the next method call.
2013-05-21 11:12:05 -07:00
Paul Tarjan e208a339d1 cleanup temporary test things
I hope our muscle memory has forgotten all these :)
2013-05-21 11:12:05 -07:00
mwilliams 227b3b7cc2 Fix bug with boxed type hints
We assumed the inner type remained the same from invocation
to invocation without guarding on it.
2013-05-21 11:12:05 -07:00
Sean Cannella 22a1609d50 remove hhir references from test runner
- remove dangling references to hhir now that it is gone
2013-05-21 11:12:05 -07:00
Jordan DeLong 943acd54c6 Fix a bug in hphp/test/run 2013-05-21 11:12:04 -07:00
Sara Golemon be9f36d3bc Always look for crypt lib, don't look for iconv twice 2013-05-20 17:07:08 -07:00
bsimmers 733abb2799 Move JIT 2013-05-20 14:41:00 -07:00
bsimmers f323a90b12 Kill runtime options related to turning off the IR 2013-05-20 14:41:00 -07:00
Paul Tarjan e1fb60cfcf Update README.md
links in code look weird
2013-05-20 14:54:46 -06:00
Sara Golemon 5e655de3d0 Remove FB specific makefile fragment from OSS repo
To rebuild generated files, see: hphp/tools/generated_files.sh help
2013-05-20 13:52:33 -07:00
Paul Tarjan 61734c80c9 clean out test_ext_magick.cpp
It looks like contbuild fails on warnings now. This file does nothing but issues a warning. If someone actually wants to test image magick, then please feel free to rever this and find a better solution, like breaking the method up.
2013-05-20 13:52:33 -07:00
Mark Williams 117823acf1 Pass name of called class to intercept handler for static methods
Otherwise there is no way to tell which class was actually called.
More context here: https://www.facebook.com/groups/243324789049477/permalink/470958322952788/
2013-05-20 13:52:33 -07:00
Sean Cannella c0cc5ef954 update idl_list.php for namespaces + lint errors
- fixes lint errors regarding generated files and generates same headers
2013-05-20 13:52:33 -07:00
Owen Yamauchi f537fa7cc1 JSON parser: fix empty dictionaries inside of dictionaries
I broke this with my change to stop boxing everything. It was dropping
empty dictionaries inside dictionaries, because the "}" of empty
dictionaries is a different parser action from the "}" of nonempty
dictionaries, and I'd neglected to update it. (The fact that no tests
caught this before is a little unsettling.)
2013-05-20 13:52:33 -07:00
Drew Paroski 9b8b31b62a Fix bug with $_SERVER['PHP_SELF']
Currently we have bug where $_SERVER['PHP_SELF'] is "" a script is invoked
at the command line without using "-f" or "--file".

This diff fixes the problem by making more places use the adjusted version
of argc/argv built using prepare_args(). This also allows us to get rid of
a old hack we've had for a long time for supporting running scripts without
using "-f" or "--file" at the command line.

Github issue 730: https://github.com/facebook/hiphop-php/issues/730
2013-05-20 13:52:33 -07:00
Drew Paroski 4d923bf679 Fix foreach with superglobals
HHVM was segfaulting on "foreach ($x as $_FILES) {}" during bytecode
emission. This diff fixes the issue.

Github issue 734: https://github.com/facebook/hiphop-php/issues/734
2013-05-20 13:52:33 -07:00
bsimmers 7f335950f9 Move more IR classes into their own headers 2013-05-20 13:52:32 -07:00
Jeff Welch 781cea6aa1 Fix extra element bug with $_SERVER['argc'] and $_SERVER['argv']
When a file is executed on the command line without the --file argument,
$_SERVER['argv'] contains an extraneous empty string at the beginning of
the array. (Note this bug does not occur when the --file argument is used.)

Github pull request 767: https://github.com/facebook/hiphop-php/pull/767
2013-05-20 13:52:32 -07:00
Drew Paroski 89765cd4f2 Make arrays implement Traversable and KeyedTraversable
This diff changes HHVM so that arrays are considered to implement the
Traversable and KeyedTraversable interfaces (which have no methods).

The idea is that these interfaces will be useful for parameter type
constraints for PHP code that wants to be compatible with both arrays and
collections (and possibly other objects that implement these interfaces).
2013-05-20 13:52:32 -07:00
Paul Tarjan 393d445193 disable tests not passing on ubuntu
I got the list from https://travis-ci.org/ptarjan/hiphop-php/builds/7268132
2013-05-20 13:52:32 -07:00
Paul Tarjan c487678d3d stop testing for locale installation
Ubuntu doesn't come with german@euro. I don't think looking for that locale was the goal of this test.
2013-05-20 13:52:32 -07:00
Paul Tarjan 26267b4a0a fix nemo for namespaces
This code was using the old assumption that namespaced functions always started with a ##\##. Instead, lets do the same thing we do in the emitter.

Closes #771
2013-05-20 13:52:32 -07:00
Jordan DeLong f4942ec853 Simplify jumpopts and the tracelet-crossing instructions
- Add ReqBindJmp, and ReqBindJmpCond instructions which emit service
    requests.

  - GuardLoc/GuardStk always imply cross-trace control flow

  - New CheckLoc/CheckStk instructions imply inside-of-trace
    control flow.
     - Renamed GuardType to CheckType to match this convention (we were
       loosly following it in the api to irtranslator, so I spread it
       through everything)

  - Check{Loc,Stk} can be optimized into SideExitGuard{Stk,Loc}

  - Reimplement jumpopts using this:
     - Check{Loc,Stk} branching to a "normal exit" can turn into
       a SyncABIRegs; SideExitGuard{Loc,Stk}.
     - A conditional jump to a normal exit followed by another normal
       exit turns into SyncABIRegs; ReqBindJmpFoo.

  - Remove the ExitTraceFoo instructions.

  - Remove IRInstruction::{get,set}TCA.

  - Remove order dependence in the ir.h enum.  (bsimmers has some
    ideas about generic branch fusion that would reduce the
    duplication there wrt this new set of similar op names; we
    discussed it and for now it seemed ok to have a whole ReqBindJmp*
    family, though.)

  - Fix the creation of unused REQ_BIND_JMPs in astubs.  I think there
    was also unused dead jumps-to-fallbacks in astubs due to the (now
    unneeded) guard-hoisting optimizations, but I haven't verified.

  - Some random cleanup along the way (adding consts to members,
    comments, removed some weird functions in codegen, etc).
2013-05-20 13:52:32 -07:00
Jordan DeLong 509a0e11dd Add assertions that no SSATmps span calls, except constants and FramePtrs 2013-05-20 13:52:32 -07:00
Paul Tarjan d088d7aa20 use chinese as the test locale
ubunut 12.04 only ships with english and chinese, so I think we should work with those.
2013-05-20 13:52:32 -07:00
Paul Tarjan a37423e4f3 stop testing the underlying library
On ubuntu mathines, this still returns PM even in the netherland's locale for both zend and us. I think we shouldn't test it.
2013-05-20 13:52:31 -07:00
Paul Tarjan 97e81277da fix ordering for test
In the open source build, this test has an inconsistent ordering. I think the underlying library doesn't maintain order of entities. Zend also has an inconsistent ordering. Lets stop testing the order.
2013-05-20 13:52:31 -07:00
Paul Tarjan 0b062c3f3b disable flakey time test 2013-05-20 13:52:31 -07:00
Jordan DeLong a9da324254 Fix a bug in simplifyDecRefStack
My bad.  If you're going to gen something with no dest in
simplifier, you need to nop out the old one.  This was leading to
over-decrefs in some cases.
2013-05-20 13:52:31 -07:00
Drew Paroski 4013bcede8 Need short array syntax here too
This corresponds to github pull request 777:
https://github.com/facebook/hiphop-php/pull/777
2013-05-20 13:52:31 -07:00
Paul Tarjan d4f8c52e9f fix uninitialized spew 2013-05-20 13:52:31 -07:00
Paul Tarjan 3f65895955 only compute variable if it will be used 2013-05-20 13:52:31 -07:00
Paul Tarjan 2a9761d838 Fix "unused variable" warnings 2013-05-20 13:52:31 -07:00
Paul Tarjan c4d32bde0f fix uninitialized warning
The open source make spewed a warning about this. How does 0 sound?
2013-05-20 13:52:31 -07:00
Paul Tarjan 8f31d3356e Add support for REQUEST_TIME_FLOAT which returns secs.usec since epoch
Zend compat http://php.net/manual/en/reserved.variables.server.php

closes 778
2013-05-20 13:52:30 -07:00
Herman Venter 23d9095d4b Add comments and split function for better readability.
As part of reading through the code of the list command, I've added some more comments and did a small refactoring to improve readability.
2013-05-20 13:52:30 -07:00
Paul Tarjan 4da410ab58 Rename closures and generators
Closures and generators are really hard to reason about in backtraces.

For generators, I took the exact name of the method and put ##$continuation##. I put it at the end so it reads exactly like a method name since in WWW we use them almost the same as the method itself.

For closures, I named the class ##Closue$Class::method#num## where num is an optional autoincrementing number.

I decided to stop prefixing the methods with ##0## which is breaking the reflection tests.

This basically redoes D782498 and D750608 but it works in repo mode.
2013-05-20 13:52:30 -07:00
Paul Tarjan f9f0d8a4f1 fix unused variable 2013-05-20 13:52:30 -07:00
Paul Tarjan 0ef4ed7b1f fix spew in open source build
These constants are defined in ##folly/Malloc.h## which is being pulled in before the jemalloc and spewing in open source builds.

Closes #673
2013-05-20 13:52:30 -07:00
Jordan DeLong 30667b7fe5 Basic support for inlining functions with parameters, inline some setters
Adds support for some functions with parameters.  Parameters
work by doing StLocs to the inlined frame, which can be eliminated if
the frame can be eliminated.  (Non-parameter locals will eventually
work similarly.)  This diff also moves all the state tracking to
updateTrackedState instead of beginInlining/endInlining functions on
TraceBuilder---the second TraceBuilder pass currently tracks state
incorrectly if the inlined frame wasn't eliminated.

This diff doesn't inline setters that have parameter type hints
because they could hold on to the frame.  Seems to be in the noise in
perflab, although contrived setter microbenchmarks definitely reflect
the change.
2013-05-20 13:52:30 -07:00
Mike Magruder fb093f8850 Add basic debugging information to crash reports
I'm adding the count of connected debuggers, and whether or not the process is hphpd, to the crash reports. In another diff I'll wire these up to hphpcrash_categorizer.py and get these as columns in the Hphpcrash Scuba data set so we can filter crash reports based on whether or not it's from hphpd, and whether or not a server was being debugged when it crashed.
2013-05-20 13:52:30 -07:00
Herman Venter f9197ff35c Use & rather than * for pointers that should never be null
This is a rather mechanical refactor that uses references (&) rather than pointers (*) for parameters that are not permitted to ever be given null arguments. In effect, the onus for checking null pointers is shifted from the callee to the caller. The & type annotation makes it clear that the callee is not prepared to deal with a null pointer.
2013-05-20 13:52:30 -07:00
Guilherme Ottoni c5e36d31af Predict that constructors return KindOfNull
If we can't infer it, then predict it.
2013-05-20 13:52:30 -07:00
Chip Turner a5f568f9d7 Add a nice error message when json failes to parse and fix Makefile rule
I had a json that wouldn't parse (trailing comma) but it was an
odd php error about iterating over a null.  So this should give a
slightly better error.

Also, .inc files are no longer used.  Remove the Makefile references.
2013-05-20 13:52:29 -07:00
Jordan DeLong dc69f1030e Flag ext-json test as bad 2013-05-20 13:52:29 -07:00
Sean Cannella c6dc5f366f ArrayIdx bytecode and IR instruction
- Implemented ArrayIdx bytecode and IR instruction for common pattern
2013-05-20 13:52:29 -07:00
Mark Williams 59f2c1749f Fewer varEnvs in generators
If the original function has a variable that the generator does not,
we create a varenv. Its not clear that that should ever happen, but
it *was* happening because:

 - closures get a magic variable called 0Closure, but generators
from closures did not.

 - unused parameters didnt get put into the variable table, so
generators with unused parameters got a varenv
2013-05-20 13:52:29 -07:00
mwilliams ca4d38d5ff Fix fb_intercept for functions with extra arguments
If you pass extra arguments to a function, and it doesn't
use any of the func_get_args type functions, by default we drop
them.

Now that fb_intercept runs after the prolog, rather than before
this means it doesnt see them. Disable the extra args optimization
when JitEnableRenameFunction is in effect.
2013-05-20 13:52:29 -07:00
Guilherme Ottoni b5d291c373 Use scratch registers that don't need REX prefix when available
Instead of using register r10 (which needs a REX prefix) as scratch
everywhere, select a cheaper scratch register for each instruction
that doesn't require a REX prefix if available.
2013-05-20 13:52:29 -07:00
Guilherme Ottoni d7708fde5b Allocate XMM registers for doubles
This diff adds support for allocating SSATmp's of type Dbl directly to
XMM registers. The register allocator now keeps per-reg-type lists of
caller/callee saved registers.  xmm0 and xmm1 are reserved for scratch
as rXMMScratch[01].

Added a runtime option HHIRAllocXMMRegs to enable/disable XMM
allocation -- if disabled, it forces all SSATmps to be allocated to GP
regs, as before.

While here, changed the conversion of int/bool consts to double from
runtime conversions to JIT-time.
2013-05-20 13:52:29 -07:00
Mark Williams 5c491af2de Don't reinitialize native funcs
The Func*'s in the native func unit are all persistent, which means
that we can strip them, and skip the Unit::merge call on every
request. But we didnt set the flag to compact the unit if the only
things that needed stripping were Func*'s. Fixed that, and also fixed
it so all the builtins are marked persistent even in non-repo-auth
mode (funcs are not if rename function is enabled, because we implement
fb_rename_function by swapping target cache entries).
2013-05-20 13:52:29 -07:00
Paul Tarjan 2ece03bbac make get_cfg_var return false
The spec says this returns false on error.
2013-05-20 13:52:28 -07:00
Guilherme Ottoni cef8173383 Document .hphp_opts test files
That's all.
2013-05-20 13:52:28 -07:00
Mark Williams 53433c3359 Fix classof for traits
Class::classof(Class* t) would always return false, if t
was a trait, but should return true if t == this.

This was causing the call_user_func in the new test to fail,
reporting that T was not a subclass of T.
2013-05-20 13:52:28 -07:00
Mike Magruder a605a5c699 Add ring logging for interesting debugging events
This adds a new trace macro to allow tracing to the ring buffer in release builds. It also performs normal tracing, too, like TRACE(n, ...). Converted a number of trace/log messages in the debugger to the new macro so we have this data when we get a core file. I've converted things that we've found useful lately, but this will be adjusted over time quite a lot as we discover new things that help us find problems more quickly, or find messages that turn our to be useless or spammy.
2013-05-20 13:52:28 -07:00
Jordan DeLong cd1888f738 Mark a couple zend tests as bad 2013-05-20 13:52:28 -07:00
Sean Cannella 0a65744bf5 rename IgnoreRedefinition to AllowOverride
IgnoreRedefinition does not do what it says it does (as the userland definition is selected) so renaming it
2013-05-20 13:52:28 -07:00
Paul Tarjan 6e391b3c51 add Facebook test suite
We've been sprinkling FB-specific stuff into other tests. I think having a dedicated suite will make it obvious where to put things. I looked at all the failing tests when running the open source build and moved them here. I also had to rejigger the flib include, since that didn't work in repo mode.
2013-05-20 13:52:28 -07:00
Paul Tarjan a7c6ad1817 add namespace reflection methods
added in 5.3

I couldn't actually get the ##sysdoc.php## to work (it just deleted all the docblocks), so I just copied the format.
2013-05-20 13:52:28 -07:00
Paul Tarjan 6f1ffc569d add php_ini_loaded_file
Since we don't support ini files, returning FALSE seems within the bounds of this function.
2013-05-20 13:52:27 -07:00
Paul Tarjan b86cce6282 document VMStackElms
This whole doc needs some love but at least it is documented.

closes #729
2013-05-20 13:52:27 -07:00
Matt Glazar d6d9955136 Allow shebang/hashbang (#!) as first line in Hack files
A shebang allow a script to be run as an executable on UNIX
systems. PHP allows shebangs, but Hack does not. This
changeset allows Hack to have shebangs like in PHP.
2013-05-20 13:52:27 -07:00
Owen Yamauchi daae3730e1 Split Xor into BitXor and LogicXor; clean up binary arithmetic
This started out as splitting Xor into two separate opcodes with more
precise type descriptions, and turned into a more sweeping change that
removes the conditional "use bool ops" logic in binary arithmetic, by
simply emitting ConvBoolToInt for bool inputs.

This will actually emit more code than before in the case of binary
operators with two bool operands. As I write this I'm crossing my
fingers and hoping that this will turn out not to matter in practice.

Also deleted some redundant if cases in codegen.
2013-05-20 13:52:26 -07:00
Paul Tarjan d8b36de433 allow namespaced classes in type args
This is a bug that running Symphony found. This part of the AST is weird as it doesn't introduce any more nodes, but I think I got it right...
2013-05-20 13:52:26 -07:00
Paul Tarjan eed19d46ac I found some more namespace tests
These all now pass with my namespace diffs
2013-05-20 13:52:26 -07:00
Mike Magruder 075926978e Segfault when calling hphpd_break() with no debugger attached
A call to hphpd_break() with no debugger attached, from a command-line run (no request), with debugging enabled (not normally true, but can be true if you use something besides cli.hdf), will segfault every time. Simple fix for a high hit-count crash.
2013-05-20 13:52:26 -07:00
Paul Tarjan 99fcd4295e canonicalize \print_r to print_r at runtime
builds on D795509.

This copies all the callsites where we autoload.
2013-05-20 13:52:26 -07:00
bsimmers 76a872c882 Fix static_assert in packed_tv build
I didn't check m_type's offset in a packed_tv build when I
first wrote this.
2013-05-20 13:52:25 -07:00
Paul Tarjan 09c139c4f7 disable flakey test
I saw this test fail on an unrelated diff
2013-05-20 13:52:25 -07:00
Jordan DeLong 5cf59f2fc1 Move another flaky zend test 2013-05-20 13:52:25 -07:00
Jordan DeLong 2f14ad8d54 Remove AllocSpill/FreeSpill
Doesn't work, so we shouldn't maintain it.  We can add a
feature like this later if we need it (although it might be easier and
just as good to just increase the preallocated spill number if
needed).
2013-05-20 13:52:25 -07:00
Andrei Alexandrescu 2baabea1ae new considered harmful
I'm committing my work on HphpArray in bite-sized pieces for easier review. This piece replaces calls to NEW with a factory method. There are many problems with operator new, starting with the fact that the allocator cannot communicate properly with the constructor.

The newly introduced factory method should return ArrayData but that causes many issues right now, so I left that step to a future diff.
2013-05-20 13:52:25 -07:00
aravind 7fbef94637 Optimize SharedVariant refcounting
Elide refcounting for non-refcounted TVs in SharedVariant.
Additionally for apc_store, if TV is a static string, use
the static version insted of the given one.
2013-05-20 13:52:25 -07:00
aravind 64889059a2 Use eager vmreganchor
This diff introduces a new "eager" vmreganchor, which we call
from some of the heaviest users of vmreganchor. For an eager
reganchor, we save the rbp, pcOff and spOff at the call site
in the MInstrState, and the reganchor itself reads it off
from the MInstrState (instead of following the rbp chain
and looking up the hash table). Currently, the set of functions
which use eager vmreganchor is based on profiling.
2013-05-20 13:52:25 -07:00
Herman Venter 5b8209aa87 DebuggerCommand::onClient and DebuggerCommand::help do not return anything meaningful.
These commands invariably return true. This is more than a tad confusing to a new reader of the code. Refactor them to return void. Remove a few pieces of dead code that would log something if they ever returned false.
2013-05-20 13:52:25 -07:00
Bert Maher 66f135b6df Add verbose option to test/run
If -v is specified print how to run the test manually even if
it doesn't fail.  Helpful for remembering how to do a
RepoAuthoritative build.
2013-05-20 13:52:24 -07:00
Paul Tarjan c0694a2ae9 name in unset error
zend does this, we should too
2013-05-20 13:52:24 -07:00
Paul Tarjan 2494ce49b5 Don't allow use Foo where Foo is already a class
Classes need to take up space in the alias map (according to zend).

Suprisingly, functions and constants don't. When importing a duplicate, zend doesn't do anything and just continues, and we currently overwrite the symbol. Should I match zend on this, or is the fact that we both continue working good enough?
2013-05-20 13:52:24 -07:00
Guilherme Ottoni 42734902fa Clean-up GenericRetDecRefs
This diff cleans some register shuffling that GenericRetDecRefs was
doing because it calls helpers that use a special ABI, in which r13 (a
callee-saved register) is not saved.

The new approach simply checks if r13 is live, and if so, pushes and
pops it around the call. This removes the need for GenericRetDecRefs
to take the function return value as a source.
2013-05-20 13:52:24 -07:00
Herman Venter 84f8764931 Clarify contract for DebuggerClient::process and remove confusing returns from helpers.
Functions that always return true may as well return nothing. That is way less confusing.
2013-05-20 13:52:24 -07:00
Drew Paroski 16a372962c Tolerate "isset($c->prop)" for collections
Currently collections define magic __get, __set, __isset, and __unset
methods which will throw exceptions if any property access is attempted
on collections (such as "isset($vec->prop)" and "$x = $vec->prop").

However, there is existing code that uses isset() to check if various
objects have a property with a certain name, and it feels like throwing
an exception here is a little harsh. This diff updates collections to
be tolerant of reading properties.
2013-05-20 13:52:24 -07:00
Jordan DeLong 5685d18e05 Fix another flakey zend test 2013-05-20 13:52:24 -07:00
Mark Williams 88ec1476e2 Fix user defined sorting
copy paste error crept in a few weeks ago, breaking the
case of a user-defined function that returns boolean.
2013-05-20 13:52:24 -07:00
Keith Adams 77d26f2bf4 Limit huge pages to the hot portion of the TC.
Huge pages are a limited system resource. When we ask for
huge chunks of system ram as huge pages, the kernel may actually do
physical memcpy's to satisfy our desires, burning CPU.

Only use huge pages on the portion of the TC that Bert's data shows to
be hot.
2013-05-20 13:52:24 -07:00
Andrei Alexandrescu 6f3b584bee Famous last bug in PolicyArray
PolicyArray pased all tests but failed in production. After browsing on my own box I figured that what happened was the method addLval() with a string key is called in production on many pages, but never in the tests. @ptarjan maybe you could look into adding such a test?

This diff still does not instantiate the policy-based array (I did instantiate it during testing).
2013-05-20 13:52:23 -07:00
Mike Magruder 64da297ced Adjust some debugger logging around the communications channel, and ensure we check all error conditions before attempting to read data from the socket
The error handling around the communication channel between client and server is a bit sketchy right now. We have some cases that are reasonable when the client is quitting and the socket is closing, and some cases where it would be surprising for this to happen. This leads to spurious messages printed out when quitting the client normally. For now, switch some of these to trace messages instead of log messages. Task 2398988 tracks cleaning this up properly.
2013-05-20 13:52:23 -07:00
Paul Tarjan b23fab2d9b Update README.md
Link to our pretty travis image
2013-05-20 14:53:50 -06:00
Paul Tarjan c30fe678f0 Merge pull request #763 from ptarjan/travis
add travis CI
2013-05-20 13:12:28 -07:00
Mark Williams 1489c698dc Use AtomicHashMap for NamedEntities and StaticStrings
Its faster as long as you have a good starting point.
Add RuntimeOptions to specify initial sizes.
2013-05-20 12:04:09 -07:00
Sara Golemon 1efb5915a0 Update folly 2013-05-20 12:04:08 -07:00
Paul Tarjan d2efdd49c0 add travis CI
To do this, I had to encode the wiki instructions in a file, which
seemed like a good thing anyways.
2013-05-18 20:23:28 -07:00
Paul Tarjan e7d8f2e54d Merge pull request #783 from rlerdorf/patch-3
Fix Bison paths
2013-05-17 22:45:17 -07:00
Rasmus Lerdorf be93cbfa08 Fix Bison paths
Some internal FB bison version thing?
2013-05-17 23:37:36 -03:00
Paul Tarjan fce1d9d636 Merge pull request #764 from ptarjan/test_whitespace
fix test whitespace
2013-05-17 13:00:03 -07:00
Paul Tarjan 3b1ca9f22d Merge pull request #770 from ptarjan/fix_cmake_patch
Fix cmake patch
2013-05-17 12:58:50 -07:00
Paul Tarjan 5c337c07aa Merge pull request #772 from ptarjan/spew
fix spew
2013-05-17 12:55:00 -07:00
Drew Paroski 92dc2dfbe1 Merge pull request #777 from rlerdorf/patch-3
Need short array syntax here too
2013-05-17 12:08:38 -07:00
Rasmus Lerdorf 4530d5d25e Need short array syntax here too 2013-05-16 15:04:16 -03:00
Paul Tarjan 92a0f8692c fix spew in folly (this is already upstream in folly) 2013-05-15 22:41:47 -07:00
Paul Tarjan 7ef447d119 change AM_CONFIG_HEADER to AC_CONFIG_HEADERS
This is needed for OSX and I think fixes a spew on others
2013-05-15 19:51:01 -07:00
Paul Tarjan 055cda0dd5 Update README.md
No printing involved, just electronic bits
2013-05-15 17:28:36 -06:00
Paul Tarjan 3019644e91 Update README.md
Relative links
2013-05-15 15:11:53 -06:00
Paul Tarjan 7e16ec7d1c Update README.md
Deeper link
2013-05-15 15:07:53 -06:00
Paul Tarjan faf9ab909f Update README.md
Examples for how to run hhvm
2013-05-15 14:33:11 -06:00
Herman Venter f7da2cfa18 Refactor DebuggerCommand.
Rename onClient to onClientImpl and move to protected space. Rename onClientD to onClient. Add comments.
2013-05-15 13:05:10 -07:00
Paul Tarjan cbd2e367c5 Move slow namespace tests back
I totally forgot about these. Lets see if they pass.
2013-05-15 13:05:10 -07:00
Mike Magruder 3522d9440f Remove races from the WebRequest debugger unit test
Got rid of our reliance on sleeps to ensure correct timing in the WebRequest debugger unit test. A change with a recent diff removed some of the races by waiting for the client to enter the busy state before sending an interrupt to mimic ctrl-c. Generalized that a bit, and extended it to ensure the initial handshake between the harness, debugger request, and the request to be debugged is correct. I've removed the 10s sleep on startup, and the 3s sleep after each notification from the various requests back to the harness. Also added a bunch of comments to hopefully explain the test better, and renamed some files/functions to better reflect what they're doing. This seems to work well on my box… I've run it a bunch in both dbg and opt builds to try to get it to fail but haven't yet. Fingers crossed ;)
2013-05-15 13:05:10 -07:00
Mike Magruder 1d68aeb876 Segfault when evaling for the debugger
Fix a sigfault when we eval a snippet of PHP for the debugger. If there is no activation record (between the end of a request and PSP, before first function execution of the request, etc.) we'd segfault setting up the invocation. Fixed to tolerate that case.
2013-05-15 13:05:10 -07:00
Paul Tarjan 9309f4c9c7 don't use aliases for functions or constants
@andrewparoski had the excellent observation that functions and constants don't get imported with use statements.
2013-05-15 13:05:10 -07:00
Edwin Smith ada1c7b2f9 Eliminate most Variant litstr methods
Doesn't eliminate the Variant(litstr) constructor, or the
same/equals/more/less/etc helpers called from comparisons.h;
those will come in a followon diff.
2013-05-15 13:05:10 -07:00
Mark Williams 86d9acaf6e Undo some #include renames
sys/*.h should use angle brackets.
Also, fix most of the lint errors for the affected files
2013-05-15 13:05:10 -07:00
Drew Paroski 2ad3ec4a14 Fix the build 2013-05-15 13:05:10 -07:00
Paul Tarjan 61c545c838 fix constant()
we don't store constants with the preceeding ##\## so slice it off. I originally edited ##name## but couldn't find a clean c++-ish way to do that. I'm open to teachings.
2013-05-15 13:05:09 -07:00
mwilliams 27601d53fd Revert "Allow shebang/hashbang (#!) as first line of Hack files"
This reverts commit d1f3c9e03d4eed7a3262bcdb461b77bbd661e5d6.

Its breaking tests
2013-05-15 13:05:09 -07:00
Bert Maher ed5d3150e3 Revert "Try inlining the LdGblAddr(Def) helpers" (commit bc1e471).
This used to look perf-neutral with a slight instruction
win... after I actually landed it, it looks like a big, consistent
negative for perf.
2013-05-15 13:05:08 -07:00
Matt Glazar eb6eb3f495 Allow shebang/hashbang (#!) as first line of Hack files
A shebang allow a script to be run as an executable on UNIX
systems.  PHP allows shebangs, but Hack does not.  This
changeset allows Hack to have shebangs like in PHP.
2013-05-15 13:05:08 -07:00
Dario Russi 0a50439fd6 InstanceOf optimization and Class::classof clean up
Changed the Set of all interfaces imlemented by a Class with an IndexedMap. Also changed the classof (and thus instanceof) to lookup in that map by name to see if an interface is imlemented by a class. That replaces the
previous mechanism that would walk the class hierarchy dereferencing PreClass in order to see if the interface was in the class inheritance. The new model seems to lead to better performance in terms of CPU instructions, lodas
and stores. The latest perflab also showed improved CPU time though that may be just lucky noise.
We have also removed the Class::classof (PreClass*) method which leads to a slightly cleaner code.
2013-05-15 13:05:07 -07:00
Mike Magruder 18f7172965 Fix breaking on request start/end/psp
Breaking at the start of the request, end of the request, or end of PSP has been broken for a while. Giving these events a site with the proper URL in them ensures that the rest of the original logic to match and stop on these breakpoints works again. Also updated the help for the breakpoint cmd using the old text from the reference, which seemed reasonable.
2013-05-15 13:05:07 -07:00
bsimmers 69dc698997 Move parts of ir.h to trace.h and cfg.h
trace.h contains the definition of the Trace class, and cfg.h
contains functions for iterating over Blocks and Traces or inspecting
their CFGs.
2013-05-15 13:05:07 -07:00
Mike Magruder 8d1ade6b3b Remove dead subclass of ThriftBuffer
PhpThriftBuffer is dead code. Removing it to make it clear that the debugger is in fact the only consumer of ThriftBuffer.
2013-05-15 13:05:06 -07:00
Owen Yamauchi 745773fd74 Hack-fix logical op types
This badly needs a proper rewrite, but this is intended to be a
low-risk, mergeable change.

These ops' destination type is always marked as Int (wrong), which meant
that the "zero extend if bool" logic was never invoked. Logical ops
always output Bool. Once we fix this, we'll save some instructions
downstream, because right now the Xor (etc.) spend an instruction
zero-extending their result, only for the next instruction to be
(usually) ConvIntToBool.

Also discovered some mildly unsettling "&" vs. "&&" issues.
2013-05-15 13:05:06 -07:00
Jordan DeLong dfbf27d243 Fix a bug with null constants
We end up with uninit nulls in the repo for unit constants.
In RepoAuthoritative mode, we will use m_type == KindOfUninit during
constant lookup to decide whether to cast TypedValue::m_data.pref to a
ConstantInfo*, and then call a function pointer that it contains.  (We
should probably also clean that up to not cast RefData*'s to
ConstantInfo*'s, but I left that out of this diff.)
2013-05-15 13:05:06 -07:00
Sara Golemon 6ec64e8bf9 make #includes consistent
I was learning from @jdelong and he said that you should use
double quotes for local includes and angle brackets for library
includes. I asked why our code was the way it was, and he said he wanted
to clean it up. I beat him to it :)

Conflicts:

	hphp/runtime/base/server/admin_request_handler.cpp
	hphp/runtime/vm/named_entity.h
2013-05-15 13:05:06 -07:00
Paul Tarjan fef62f03a2 kill VM namespace
Now that HHVM is the default runtime, this namespace doesn't mean anything.
2013-05-15 13:05:05 -07:00
Paul Tarjan b24ca4a2b1 flakey test 2013-05-15 13:05:05 -07:00
Mark Williams aacaa37ad5 Opimize re-entry path
Use the jitted prologs, and add a "few args" re-entry
point to avoid the overhead of creating an Array
2013-05-15 13:05:05 -07:00
bsimmers 72d0e84e1b Optimize string offset setting
I was looking at this code while working on a vector
translator diff and noticed that we're doing some unnecessary
refcounting.
2013-05-15 13:05:05 -07:00
bsimmers e518e102e6 Predict that the result of SetM is the same as its input
If we can't prove at compile time that a set operation won't
fail, we don't know the exact type of SetM's stack output. Since these
failures should be extremely rare, we now predict that the set
operation won't fail and side exit if it did. This converts a bunch of
DecRefs to DecRefNZ, and when we get rid of all the SpillStacks for
the helper calls this will allow us to optimize away those
IncRef/DecRefNZ pairs (while pushing the IncRef to the exit trace).
2013-05-15 13:05:05 -07:00
Herman Venter 6afb27bf50 Clean up handling of debugger quit command
Set the stopped flag for the debugger proxy when it receives a quit command, so that the proxy exits a bit quicker and cleaner. Add a timeout to the cleanup quite of test_debugger, so that it does not hang when a test goes wrong. Add some more tracing.
2013-05-15 13:05:05 -07:00
Jordan DeLong 19562faabc Translator analyze assumed strlen($x) is always an int
This was leading to people getting (int)&some_null_variant as
the result of strlen.  I think this came about when we implemented the
5.4 strlen semantics (we stopped returning 5 for strlen(array()),
etc.)
2013-05-15 13:05:04 -07:00
Paul Tarjan 8538894fd4 call autoloader with correct case
on github, closes #738
2013-05-15 13:05:04 -07:00
Drew Paroski a8d84e2f21 Refactor HipHopSyntax and HackMode to play nice 2013-05-15 13:05:04 -07:00
Bert Maher 239c9af6cd Try inlining the LdGblAddr(Def) helpers
LdGblAddr and LdGblAddrDef call helpers that are really thin
wrappers.  Seems like it might be a good idea to just emit code
directly into the TC to avoid the extra call.
2013-05-15 13:05:04 -07:00
Jordan DeLong 66b22c9c52 Don't malloc from a signal handler
This can self-deadlock the process.  Instead, pass the reason
to the server so it can log it after the signal handler exits.
2013-05-15 13:05:04 -07:00
Paul Tarjan 0d2f72307b don't use the whole namespace when we only want one thing 2013-05-15 13:05:04 -07:00
Paul Tarjan 35e75ffd97 getting ready to kill VM::
These will need to stay qualified.
2013-05-15 13:05:04 -07:00
Herman Venter f411d5dde9 Use the same repo for config-debugger-server.hdf as is used by cli.hdf.
When the debugger tests run, the repo location defaults to ~. This leads to failures when the network is slow.
2013-05-15 13:05:04 -07:00
Alok Menghrajani db9577b140 Rename strict with Hack
Strict mode was the old name. Let's avoid any confusion in the future and rename things.
2013-05-15 13:05:03 -07:00
bsimmers 997484ffcd Disable test/zend/good/ext-standard-strings/setlocale_basic2.php
It's failing/flaky.
2013-05-15 13:05:03 -07:00
Paul Tarjan 1e0f032ba7 absorb comments on namespaces
This test didn't really intentionally test this, but it caught us not eating comments on namespaces.

I don't understand the difference between ##ParserBase## and ##Parser##. Maybe this belongs here? It needed to be here to have access to ##pushComment##.
2013-05-15 13:05:03 -07:00
Paul Tarjan 06cb6611dc handle closing tag in ?>
I wanted to get closer to zend's implementation but they seem to do scanning and parsing at the same time. We don't have the state of the parser when the scanner sees the ##?>## token. I think this is the next best thing if we don't want the refactor of D808985
2013-05-15 13:05:03 -07:00
Jordan DeLong 230d2ae5e6 Reduce number of threads during initial hhvm startup
Before we've jitted the first bit of the TC, having so many
threads leads to a pathological situation: we accept a bunch of
requests (135) and have all of them running in the interpeter,
starving the JIT thread that is trying to make them all go faster.
(Perf record of a machine in this situation shows the vast majority of
the time in dispatchImpl, SrcDB::find, and enterTC).  This diff tries
to solve this by limiting the number of threads to the number of cores
for the first N requests.
2013-05-15 13:05:03 -07:00
Jordan DeLong 8bf9e83eaf Delay registration of SIGCHLD handler until after lwp fork
I think the cause of our issues with random failed-to-exec
errors is this SIGCHLD handler.  When the parent process asks a light
process to do a waitpid operation, we now can get EINTR for two
reasons.  It used to use signals only for implementing timeouts with
SIGALRM, but now it appears possible due to the SIGCHLD.  This could
lead us to report the waitpid as failing---which it looks can have
ExecFuture thinking running==false and reading the exit code as -1.

Also, now that we have a SIGCHLD handler (are we sure we want to keep
this?), using waitpid() without an EINTR loop is probably similarly
broken in the parent process.  (Also, isn't it basically incorrect to
use wait functions without an EINTR loop in general, though?)  I
didn't add an EINTR loop in do_waitpid in this diff because it's using
signals for timeout (it really should be checking a volatile
sigatomic_t that gets set by the handler, though)

Also, this means using Process::Exec is suspect in general.  All uses
looked like debugger or tests only (and when hphpc runs hhvm in a
subprocess), so I didn't nuke them (yet).  I deleted some random
network.h dead code that uses it, though.
2013-05-15 13:05:03 -07:00
Jordan DeLong df1308cb9d Add hack to register checker for rbp
Rbp is allocated just as weirdly as rbx.  I was able to hit
this assert on a inlined function that didn't eliminate the ActRec
(there are ReDefSP's that consume rbp).
2013-05-15 13:05:03 -07:00
Paul Tarjan 126594a759 Be less explicit about namespace
I'm getting ready to kill the VM namespace. I'll be doing small cleanups first.
2013-05-15 13:05:03 -07:00
Paul Tarjan 52c9b25ae8 kill dead code
When trying to figure out what this was I figured out it wasn't anything.
2013-05-15 13:05:03 -07:00
Jordan DeLong 6546c3edf6 Don't hoist LdLocs to the top of tracelets.
We have separate GuardLoc instructions now.  This was
originally intended to be an optimization (and LdLoc was
simultaneously acting as the guard back then), but now that
Rematerialization is off (and since we don't do a DCE after register
allocation anyway) I am doubtful.
2013-05-15 13:05:02 -07:00
Jordan DeLong f6a2dd1b4f Move ir inlining tests to slow/ir_inlining, add case for bug @mwilliams found
Mark hit a bug that aravind already fixed where we didn't set
stackDeficit to zero after ending an inlined call.  Adds the repro
case and moves all the tests to slow.
2013-05-15 13:05:02 -07:00
Edwin Smith b4c6a50f78 Add a register-allocator-validator.
This adds a checkRegisters() function so we can assert if the register
allocator botched something.  Our IR already must pass SSA rules after
register allocation, so its enough to scan the code in dominator
preorder, keeping track of what SSATmp is in each register and spill-slot.
Then at the point of each use, we can assert that the register/slot assigned
to the input tmp actually contains that input tmp.

While I was at it, I moved checkCfg() and checkRegisters() to the new
check.cpp file, and factored out findDomChildren().

Also, this checker failed on a tracelet that used exactly 16 slots due
to the +1 fudge factor added by LinearScan::preAllocSpillLoc.  I fixed
this by changing the meaning of spill slots; now they are logical
slot numbers, and we have a dedicated spillSlotOffset() function
to compute the offset from RSP.  This can be updated in the future
to handle more than just the preallocated spill slots.
2013-05-15 13:05:02 -07:00
Paul Tarjan d7ce66ff73 loosen catchable error message
zend emits a special error for typehint violations. We aren't going to be string compatabile with this as they emit 2 line numbers and files. Lets just make sure we fatal at the same point in the test.
2013-05-15 13:05:02 -07:00
Edwin Smith 17a323c050 Rename IRInstruction's iid property to id.
I called it iid because id was taken by the linear-scan specific
'id' field, which really was a linear number and could change.
Now that we have LifetimeInfo.linear[inst], we can use the name
id consistently between SSATmp, IRInstruction, and Block.

This in turn allows StateVector to be one iota simpler.  Renamed
count to numIds while I was at it.
2013-05-15 13:05:02 -07:00
Paul Tarjan 2f023e66db allow \ in function types
I looked at all the other uses of ##ident## and I think they are correct to not allow namespaces but we'll see.
2013-05-15 13:05:02 -07:00
Paul Tarjan efbb53323e clear aliases between namespaces 2013-05-15 13:05:02 -07:00
Guilherme Ottoni 3980fb9ff6 Add missing check for InterpOne following a CG_PUNT
I forgot this check in my original diff: we need to make sure that
bytecode instruction that cause the CG_PUNT has support for InterpOne.
Just a couple of instructions don't have InterpOne support, so this
was not causing any problems.  But the check should be there anyway,
for when we start porting to other ISAs.
2013-05-15 13:05:02 -07:00
Paul Tarjan 96e793360b function and constant fallback for namespaces
It turned out a lot of the namespace stuff still worked. The biggest thing for the first pass is that we don't fallback to the global function or constant if there isn't a namespaced one.

Also, when a constant has a ##\## anywhere in it it throw an error when it isn't defined, instead of assuming the string.
2013-05-15 13:05:01 -07:00
Guilherme Ottoni 8c7ba8c05c interpOne instructions that fail at code-gen
This avoids running to whole tracelet with a backup, slower engine
(interpreter or Tx64).

This will also help with the ARM port: we can initially CG_PUNT on all
IR instructions, and add support for them incrementally (without
sending the whole tracelet to the interpreter).
2013-05-15 13:05:01 -07:00
aalexandre 9559dcf879 PolicyArray initial review
PolicyArray splits the ArrayData implementation in two parts. ArrayShell implements the baroque ArrayData implementation in terms of a much smaller statically-bound core that concerns itself exclusively with the storage strategy for the array. This way the two aspects can be worked on separately, and different stores can be easily plugged into the given ArrayShell.

To give a better perspective, the featured SimpleArrayStore has about 340 lines all told (including solid documentation), whereas ArrayShell has some 1100 lines. The shell can be reused with other stores of unbounded sophistication. The store needs to implement only 22 primitives, some of which are trivial. Basically a new store implementation saves 1100 of difficult-to-get-right lines of code right off the bat, and only needs to focus on implementing 22 well-defined primitives.

Things to watch for when reviewing:

- Is the store API small/expressive enough? What should be added/removed?

- Are various forms of duplication present? If so, how could code be factored better?

- Any subtle change in semantics from HphpArray and friends that should be minded?

Known issues:

* Currently ArrayShell is defined as:

  class ArrayShell : public ArrayData, private SimpleArrayStore { ... };

when in fact it should be:

  template <class StorePolicy>
  class ArrayShell : public ArrayData, private StorePolicy { ... };

Extenuating circumstances related to allocator design prevent use of templates at this point. I'll work on these in parallel with the review.

* growNoResize is almost always prefaced by a test-and-grow. This sequence should be encoded in a function.

* The growth policy is spread all over the place in a subtle form of duplication.

* The current store design makes almost no effort to be particularly efficient.
2013-05-15 13:05:01 -07:00
Paul Tarjan 994ce35b82 cleanup lookupFunc
This func took 2 params and ignored the second one. While I was there I made the functions call eachother. Hopefully inlining is smart enough to let me clean this code.

I got a bit carried away, but I think this is better.
2013-05-15 13:05:01 -07:00
Paul Tarjan 27671d63b9 Update README.md 2013-05-15 13:56:30 -06:00
Paul Tarjan 234e1a5973 fix test whitespace
somehow this whitespace got eaten by the opensourcing
2013-05-13 00:52:37 -07:00
Sara Golemon 239bad931c Localize MySQL.Localize option to Facebook build only
This extension to the mysql php-api relies
on internal libmysqlclient functions which are deprecated
from normal MySQL builds.  Just turn it off and use fallback
behavior instead.
2013-05-10 10:54:42 -07:00
Mike Magruder 4e407b85ad Fix bug with preventing returns to TC for debugger
In order to ensure that we can continue to interpret code when setting up a step out, even if we're stepping out to jitted code, we set the saved RIP in each ActRec on the stack to the retFromInterpretedFrame() helper. However, this is wrong for generator functions. There is a different variant of the function for generators, so use that when appropriate. Also added a check to ensure we only changed return addresses to jitted code. Mark thought of a rare case where we could have a return address to a C++ helper in there, so leave those alone.
2013-05-10 10:54:42 -07:00
Mike Magruder 18528568fa Disable the debugger's Instrument command, and remove the code that checks for instrumentation from the interpreter
The debugger's Instrument command does not work with the JIT; any instrumentation requests will be ignored for jitted code. We believe that no one is using this at this time. I'm starting with a small diff to disable the command and remove the impact it has on the interpreter for now, just in case we're wrong. Once the command has been disabled for a few weeks I'll come back and remove all of the code (task 2376711).

InstHelpers was just pure dead code, so I nuked it.
2013-05-10 10:54:42 -07:00
Edwin Smith 9f338c96f9 Remove Variant::operator[](litstr)
And its remaining call sites.
2013-05-10 10:54:41 -07:00
Herman Venter b91dd81677 Improve readability of break point code in debugger.
Added comments to every method in cmd_breakpoint.cpp. Also renamed some methods to make their intent more obvious. Moved a few implementation methods from the public to protected space.
2013-05-10 10:54:41 -07:00
Paul Tarjan 930d45ceb3 fix flakey test
scanning the current directory sucks
2013-05-10 10:54:41 -07:00
Guilherme Ottoni 39416bcaa5 Use target cache for static properties of persistent classes
Accessibility of properties of persistent classes can be checked at JIT
time, so use the SProp-based fast path for these cases too.

Also, enhance HhbcTranslator to try to emit LdClsPropAddrCached,
instead of relying on the Simplifier to transform LdClsPropAddr into
LdClsPropAddrCached.  Doing this only in the Simplifier results in
unecessary ExceptionBarrier before LdClsPropAddrCached.  However,
there's still value in keeping the optimization in the Simplifier, so
that it can leverage opportunities exposed by other optimizations.  So
factor out the logic to check whether to use the SProp cache.
2013-05-10 10:54:40 -07:00
Bert Maher 083b028a3d Implement fast allocation path for objects in HHIR
Tx64 generates a fast path for allocating objects of a
persistent class that inlines a bunch of the helper work into the TC.
This diff is basically a translation of that path into HHIR codegen.
2013-05-10 10:54:40 -07:00
Herman Venter 3abc997a4e Rewrite parser for break point specification.
The specification string following a break command was parsed by means of ad-hoc string splitting and sub string finding. This scheme cannot deal with namespaces and class names that contain : (such as xhp classes). There is now a proper parser for break point specifications. Also, xhp class names are mangled before putting them in the BreakPointInfo structure, otherwise breakpoints qualified with xhp classes will not be hit. The syntax for namespaces has been changed to fit the language and if present namespaces are used to mangle function and class names, so that they match the names produced by the regular parser.
2013-05-10 10:54:40 -07:00
Ben Maurer e0f8f5bdff Use equals() in equals(StringData, StringData)
Equals is faster in a few ways.
(1) no call to memcmp unless string sizes are the same
(2) does a fast check for either of the strings being static
    before any calls to is_numeric_string
2013-05-10 10:54:39 -07:00
Owen Yamauchi c2e56ad8f3 Implement IsObject in IR
It turns out is_object actually shouldn't be calling isResource, so this
really wasn't as bad as everyone thought. I cleaned up the simplifier
logic for this instruction (even though is_object is weird, we can still
optimize it away when the src isn't even KindOfObject).

A more elegant solution might be to introduce Type::Resource, but that
would be more complex and I just want to get something working for the
purposes of lockdown.
2013-05-10 10:54:39 -07:00
Owen Yamauchi 09639ff073 Fix is_object on resources
PHP certainly never runs out of fun surprises to spring on me!
2013-05-10 10:54:39 -07:00
bsimmers 7bce06f37f Tune some VectorTranslator helpers
vGet*Impl were always returning TypedValues with m_type ==
KindOfRef so I just made them return RefData*. cGet*Impl were doing
some unecessary copying of TypedValues.
2013-05-10 10:54:38 -07:00
bsimmers 9b4e79aa5e tx64's vector helpers are no longer hot
This is cheating wrt tx64 vs. hhir but that battle's already
been decided. We should be able to just remove these completely soon.
2013-05-10 10:54:38 -07:00
Jordan DeLong 4601297ae8 Make a toVariant() function on ArrayInit @override-unit-failures
Suggested by @smith.
2013-05-10 10:54:38 -07:00
Jordan DeLong abd3808eb3 Minor improvements to ArrayInit
Remove implicit conversion operator.  Also found some apc
code that relied on copy elision for correctness.
2013-05-10 10:54:37 -07:00
Owen Yamauchi a6663759d2 Stop boxing everything in the JSON parser
The JSON parser was producing structures that held all arrays in
RefData. This was to defeat copy-on-write, since ArrayDatas were
referenced from multiple places (i.e. the parser's internal stack of
in-flight objects, and the actual structure being built) and mutated. I
rectified this by not adding arrays into the overall structure until
they're done being modified. This necessitated introducing a separate
stack for keys, to handle this structure:

  { "key": { ... } }

When we see the opening { of the inner object, we push "key" onto the
stack, so that when we see the closing } of the inner object, we can
store it into the outer object under the right key.
2013-05-10 10:54:37 -07:00
Edwin Smith 494733bd31 Remove Array::operator[](litstr)
Refactor the remaining uses of litstr-indexed Array, and
get rid of the operator overload.
2013-05-10 10:54:37 -07:00
Mike Magruder e967eb197f Add more server-side debugger logging, small tweaks to server-side error paths
Added some more logging on the server when debugging. Log warnings during shutdown (normal and from the signal handler) when there are debuggers attached. Minor tweaks to some of the error handling paths, with more log messages instead of silent failures. Also moved server-side closing of the thrift buffer to proxy destruction.
2013-05-10 10:54:24 -07:00
Paul Tarjan 0aad5e95bf support pcre ini options 2013-05-09 11:38:06 -07:00
Paul Tarjan b3ededfdc6 fix flakey text
reported by @aalexandre. Sharing filenames is bad.

done with

  ./tools/import_zend_test.py -z /tmp/php-5.4.13/ -o bug41445
2013-05-09 11:37:58 -07:00
Paul Tarjan bb37e7c5f2 Disable flakey test 2013-05-09 11:37:42 -07:00
Mark Williams 1e75626704 Keep track of whether we're jitting or not
Rather than test RuntimeOption::EvalJit and 5 thread locals to determine
whether or not to run the jit on each re-entry, maintain one thread local.
Make various RequestInjectionData fields private to ensure that the jit
flag is kept in sync.
2013-05-09 11:37:41 -07:00
Drew Paroski 7ff13c1906 Remove more ClassInfo goo
Remove more uses of ClassInfo in favor of VM::Class, VM::Func, etc.
2013-05-09 11:37:41 -07:00
Edwin Smith e1ee546e33 Move register allocator fields out of SSATmp
These are not used except between linearscan and codegen,
so put them in a StateVector instead.
2013-05-09 11:37:40 -07:00
aravind b3bcab18be Inline FPushCtor
Similar to FPushCtorD
2013-05-09 11:37:40 -07:00
bsimmers 120ed539e4 Clean up IR printing
This creates a tracemod that does nothing but print the IR
(printir). I reworked the levels a little so you can reduce the number
of passes that are followed by a dump of the IR. I'm open to
suggestions on the order I set up in print.h.
2013-05-09 11:37:40 -07:00
Mark Williams bf0dd20fef Rewrite fb_intercept to use the FunctionEnter hook
This cleans up the code a lot, and takes it out of various hot
paths. It will impact perf for requests where intercepts are used,
but no longer penalizes requests that don't use intercepts.
2013-05-09 11:37:39 -07:00
Paul Tarjan c4357440b0 slice up builtin_extension
This .expectf files turns into a huge regex and is our largest one. Instead lets have many small tests.

I made it with some fancy bash script.
2013-05-09 11:37:39 -07:00
Paul Tarjan 155aeba44b Fix tests not able to run in parallel
Reusing filenames is bad.
2013-05-09 11:37:09 -07:00
Sean Cannella 7651d0d57b Don't show line number/file for generator psuedo methods. 2013-05-09 11:34:36 -07:00
Guilherme Ottoni e4231921e3 Enable translation of BindS
The code was there, but we were still punting.
2013-05-09 11:34:35 -07:00
Paul Tarjan a220ce802f Enforce disable of flakey tests
This will make future imports of these not re-enable them
2013-05-09 11:34:13 -07:00
Edwin Smith 494e87cbd1 Move m_id and m_lastUseId to LifetimeInfo
These two fields represent the results of liveness analysis,
so group them together that way.
2013-05-09 11:34:12 -07:00
Jordan DeLong d467787a45 Use ArrayInit in debugBacktrace
Presize the arrays.
2013-05-09 11:34:12 -07:00
Jordan DeLong 774fbc7d16 Move static strings out of debugBacktrace
We're paying for some null checks here each time we do a
backtrace.  Inspected all usage sites of the other StaticStrings to
ensure adding "consts" shouldn't change behavior (similar to that
ternary operator issue @smith ran into).  Also remove a bunch of
temporary smart pointers that we don't need anymore.
2013-05-09 11:34:12 -07:00
Jordan DeLong 6b8e5611d6 Make it unnecessary to null out locals during RetC
We already look up the PC for every frame as we're taking the
backtrace, so we can just skip them when going through a backtrace
frame.  Also, there is currently a guarantee that if an exception
propagates through a frame where pc was pointing at RetC, all the
locals and the $this pointer have already been decref'd, so we don't
need to use a null check to determine this.
2013-05-09 11:34:11 -07:00
Paul Tarjan 8047bac356 line up stuff
These are the only braces not lined up on that column in this file.
2013-05-09 11:33:53 -07:00
Jordan DeLong 5b7a3e3895 Clean up and document SRFlags
Make it part of abi-x64.h and explain what the flags mean.
2013-05-09 11:33:52 -07:00
Jordan DeLong 27fa04f132 Clear local related helpers out of TraceBuilder
Optimizations went to Simplifier or preOptimize (or were
removed in some cases where they duplicated things already done in
simplifier), php-semantics went to hhbctranslator.
2013-05-09 11:33:52 -07:00
bsimmers ce48632a40 Don't template on op for SetOpProp and IncDecProp
The only difference between each template specialization was
the op they were passing into a rather deep chain of helpers. None of
them are very common either, so it's not worth the code bloat.

Unfortunately the setOpProp helpers now need 7 qwords of arguments so
one of them has to be passed on the stack. I added support for that to
codegen.
2013-05-09 11:33:52 -07:00
Paul Tarjan e731304d3d make test/run work on stock PHP
I want people to start contributing to us from the community. I think them running the tests would be a good idea on any patch. I don't really want to assume they replaced their php binary with hhvm just yet, so I think the test runner should work on whatever php is in the path
2013-05-09 11:33:23 -07:00
Erling Ellingsen 1e78ff4999 Allow type aliases to take (ignored) type arguments
type Foo<T> = Bar<T,T> is treated as Foo = Bar; Foo<T> = @?T isn't supported.
2013-05-09 11:33:23 -07:00
aravind b558f6f118 Inline object constructors
This should automatically handle the case when we had
a generated 86pinit constructor.
2013-05-09 11:33:23 -07:00
Jan Oravec 4780da0ed7 Add missing #include
Add missing #include.
2013-05-09 11:33:22 -07:00
Edwin Smith 8985169828 Move spillslot field from SSATmp to linearscan pass
Spillslot is an internal field for the linear scan pass,
we don't want it in SSATmp.
2013-05-09 11:33:22 -07:00
Jan Oravec f2cf5fbaac Provide safe storage for private PHP data in external thread events
Sometimes, a PHP object (usually defined by extension) is needed to
unserialize the data.

Provide a safe mechanism to store such object with external thread
events.
2013-05-09 11:33:22 -07:00
Jordan DeLong cc57737f6b Disable some flaky zend tests @override-unit-failures 2013-05-09 11:33:21 -07:00
Edwin Smith 957b19d088 Move m_liveRegs out of IRInstruction
The live regs field in IRInstruction is the result of an analysis
pass which can be better encapsulated by moving the field into
its own StateVector.
2013-05-09 11:33:21 -07:00
Paul Tarjan 257825efa5 re-enable tests
These were reported (correctly) as crappy and disabled in D801504. I fixed them.
2013-05-09 11:33:21 -07:00
Andrei Alexandrescu e6ff1ebf2c Eliminate circular dependency in SmartAllocator
SmartAllocator defined and used an enum for each type using smart allocation, thus closing a circular dependency loop. In fact the enum is not necessary and can be replaced with typeid with relative ease. While at it I've also simplified GarbageList a bit.

Also fixed a couple of lint errors.

Perflab completed, looks neutral to good: https://our.intern.facebook.com/intern/perflab/details.php?eq_id=399305
2013-05-09 11:33:20 -07:00
Philippe Ajoux e551d3918f add hooks to ASIO to allow building of dependency graphs in PHP
In order to build a dependency graph of continuation execution and data-fetching in PHP-land, we need a few instrumentation points in the asio_ext HHVM extension. There are 4 additions required:
   1. Callback when a continuation finishes successfully.
   2. Callback when a continuation blocks on a wait_handle.
   3. Get array of WaitHandles a GenArrayWaitHandle is waiting on.
   4. Get WaitHandle that the SetResultToRefWaitHandle is waiting on.
I don't think this should really affect performance, as in the normal case, nothing has changed, but you never know... I'm also not sure who should be reviewing this, so I've just added @jan for now. If you could pile other people on, that would be cool.

sandcastle appears to be broken.
2013-05-09 11:33:20 -07:00
Edwin Smith 4fdec8b2a1 Move pretty-printing code into its own file
Pretty-printing the IR is a kind of pass, and definitely a separate
concern, just like rendering IR as machine code.  Put it in its own file.
2013-05-09 11:33:19 -07:00
Wez Furlong d1e4f65ec9 proc_open should inherit g_context->m_envs
Some head scratching until I realized that my `putenv()` calls
in my PHP script weren't actually changing the environment for subsequent
`proc_open()` calls.

What I'd like this diff to do (and I fully expect that I'm violating some
referencing rules in hhvm) is to fall back to using our current view of
the environment as maintained in the execution context in the case that
proc_open is not explicitly passed an environment array.

I think I've even added a test to prove that this works, but I haven't
read the manual and fbmake runtests takes too long, so I'm just going
ahead to submit this diff.
2013-05-09 11:33:11 -07:00
Sara Golemon 708d16ca32 Merge pull request #758 from tstarling/master
Add missing macros to timelib_config.h
2013-05-08 20:39:07 -07:00
Tim Starling 9832e88a27 Add missing macros to timelib_config.h
The absence of HAVE_LIMITS_H caused timelib_structs.h to define LONG_MIN
and LONG_MAX to be 32-bit values, which caused timelib_date_to_int() to
give an error for a date after 2038, which caused the current time to be
returned for e.g. date_create('28 July 2038')->format('r').

The issue was detected by MediaWiki unit tests, and this fix was tested
by the same method.

While I was at it, I also added HAVE_LOCALE_H, which was checked for in
CMakeLists.txt but not used, and I fixed the definition of SIZEOF_INT
(#cmakedefine doesn't work that way). I arranged the macros in
timelib_config.h.cmake in the same order as they are in CMakeLists.txt.
2013-05-09 12:41:14 +10:00
jdelong dcd704f2f3 Minor cleanup in srcdb.h
Mainly gets rid of the need to pass Asm& a and astubs
to all the patching functions.
2013-05-07 10:56:32 -07:00
Guilherme Ottoni a111aaa518 Streamline exits from HHIR to Interp when Tx64 is off
If Tx64 is disabled, change slow exits to call the interpreter directly.
2013-05-07 10:55:32 -07:00
bsimmers 8436050f1f Use traceRelease for Eval.DumpBytecode
This shouldn't be restricted to debug builds.
2013-05-07 10:55:32 -07:00
bsimmers d559b8f1e1 Disable some zend tests reported as flaky 2013-05-07 10:55:32 -07:00
bsimmers 983a68a4b7 Fix runtime options for tests
My diff to turn the ir on by default missed a few places that
need HHIRDisableTx64=0.
2013-05-07 10:55:32 -07:00
Mike Magruder ed8fb402c0 Improve the Next command to not interpret and single-step ever line under calls from the original source line
This improves both Next and Out to avoid interpreting and stepping everything between when they start and finish. Out now lets the program run free until a pseudo-breakpoint at the return site it hit. Next continues to single-step the source line being stepped over, but now lets the program run free under calls made from that line.

The logic in Next regarding "calls made from that line" is extremely generic. We don't look at, say, call opcodes and decide to do something special. Rather, when we find we're off the original source line and a frame deeper we setup a "step out" operation much like the Out command then let the program run free. When we reach our return point, we continue stepping like normal. This accounts for not just calls, but iterators, and anything else that causes more PHP to run under the original source line.

This change moves the flow control logic down in to the respective cmds: Next, Step, Out, Continue. These cmds get a crack at executing at various points in the interrupt/command processing path. These cmds now own setting up the last location filter, whether they need VM interrupts, and whether they're done or not.
2013-05-07 10:55:31 -07:00
Guilherme Ottoni 0cd3186819 Fix trace exit type for IncDecL of boxed values
For accesses to boxed locals, if the inner type changes, we can
retranslate using HHIR: the new translation will inspect the live type
and be able to execute the instruction.  While looking at something
else, I noticed that in such cases IncDecL was taking a slow exit
(which avoids using HHIR).
2013-05-07 10:55:31 -07:00
Jordan DeLong 2d376658d9 Move remaining stack optimizations to simplifier
Removes all their genFoo functions and does the corresponding
work in Simplifier, since it requires no state.
2013-05-07 10:55:31 -07:00
Jordan DeLong f8ae6b7149 Add a OpNot to HHIR; remove TraceBuilder::genNot
There's always been a little weirdness in the simplifier with
regard to negation.  Apparently I used to think it could lead to
losing a ConvToBool (I am not 100% sure what the case that comment
refered to was now though).  It definitely lets us avoid some
zero-extending bools to ints though (since our binary arith guys don't
support bools yet), and with this the last "dubious" genFoo is gone.
2013-05-07 10:55:30 -07:00
Jordan DeLong 71a51b31ec Minor tweaks to StateVector @override-unit-failures
- Move to state_vector.h
- Use smart::vector instead of std::vector
- Make factoryId and count helpers private
- Add const_iterator support
- Make grow() use resize() instead of looping push_back().
- Use assign() in reset().
2013-05-07 10:55:30 -07:00
Edwin Smith 08693f9d6f Only rematerialize instructions when its safe to.
Only rematerialize an instruction if its inputs are still live
and in registers at the point we're cloning it, which, given the current state of flux in the register allocator, is restricted for
now to just instructions that consume rVmSp, rVmFp, or immediate constants.
2013-05-07 10:55:30 -07:00
Sara Golemon 497a22c04f Fix endianness for all tiger algos
The PHP version the implementations in hphp were based off of
had wrong byte ordering.  Fix them in line with PHP having been fixed.
2013-05-06 10:31:24 -07:00
Sara Golemon 2dcca1dded Add fnv1a?(32|64) hash algos
Split out of my previous "fix varios hash algos" diff.
This diff adds the fnv132, fnv1a32, fnv164, and fnv1a64 algorithms
2013-05-06 10:31:24 -07:00
Sara Golemon c121b10e13 Add SHA224 hash algo
Split out of my earlier "fix varios hash algos" diff
This diff only adds sha224.
The fix for tiger and the add of fnv are in different diffs.
2013-05-06 10:31:24 -07:00
Edwin Smith bdb7e9428e Remove emitSmashableFwdJump() and appendSrc()
Dead code.
2013-05-06 09:53:49 -07:00
Rasmus Lerdorf 2b23084f39 Fix program args not having a space
When inputs.size() is 1 and we have programArgs,
we wind up squashing those two values together.

Be pessimistic and always add the space in.
2013-05-06 09:53:36 -07:00
Edwin Smith 36a27765d2 Use a DCE-local state vector for use counts
Moving more pass-specific information out of SSATmp.
2013-05-06 09:31:45 -07:00
Drew Paroski 697bca0182 Improve var_export for collections
The current output of var_export for collections isn't very useful. It
outputs a call to __set_state like so:

  Map::__set_state(array(..))

This isn't particularly useful since collections don't implement the
__set_state() method, and it is also suboptimal for the design of
collections since it relies on using PHP arrays.

This diff changes var_export to use collection literal syntax for
collections instead of generating a call to __set_state().
2013-05-06 09:31:44 -07:00
Drew Paroski 7f97e9d784 Remove "const char* cls" parameter from cppext static methods
For cppext static methods we have a "ti_" method that takes an extra unused
parameter "const char* cls" and then a "t_" wrapper method that calls the
"ti_" method.

This makes things unnecessarily complicated when writing HipHop extensions.
Let's get rid of the extra unused parameter "cls" and the unnecessary "t_"
wrapper method.
2013-05-06 09:31:44 -07:00
Paul Tarjan 6589da0e87 lots of race conditions in zlib 2013-05-06 09:31:39 -07:00
Sara Golemon 0bfab33ce9 Fix logic fail and unsets in DefineConstant()
If we infer the type, then we already know
its integer type ID.  Trying to then parse that type
leads to "Undefined type" errors (but it still functions
due to the fallthrough).

This diff skips trying to parse a known type and thus
avoids the misleading error message.

Also guard against missing funcs/consts elements in
global scope and classes.
2013-05-06 09:31:38 -07:00
bsimmers 59beab1596 Don't dereference a null array in our SIGCHLD handler
Sometimes this array is destructed by the time the handler is
called.
2013-05-06 09:31:38 -07:00
Mark Williams 270227c36c Don't leak cloned closures/continuations
Instead of appending the new closure to the end of the list,
the list was being cleared, and then the new closure was added.

Most closures only get one clone (since we don't yet support bind)
but occaisionally, closures (or continuations in closures) inside
traits can end up with more than one. In that case, we ping-pong
between the different clones, generating new clones, and new code
as we go.
2013-05-06 09:31:38 -07:00
Edwin Smith 302acd0941 Remove extraneous trace->print() causing double listings
Accidental call.
2013-05-06 09:31:38 -07:00
Mark Williams a32d993f1f Fix remaining QuickRepoJitIR test, and enable them
We intentionally drop some notices in production by default.
Add an opts file to prevent that.
2013-05-06 09:31:37 -07:00
Drew Paroski 21b8949d23 Make array_key_exists support collections efficiently
array_key_exists() was converting collections to arrays before checking if
a key exists, which is an O(n) operation (which also has the annoying side
effect of changing int-like string keys to int keys.)

This diff makes array_key_exists natively support collections (which also
addresses the pesky int-like string key -> int key issue).
2013-05-06 09:31:37 -07:00
Jan Oravec 4e169c6bda Remove deprecated ContinuationWaitHandle::start()
ContinuationWaitHandle::start() was deprecated in favor of Awaitable
interface's getWaitHandle().

Remove ContinuationWaitHandle::start() from public API and rename it
internally to c_ContinuationWaitHandle::Create() that is called only from
Continuation's getWaitHandle(). Since it is guaranteed that the
Continuation does not have associated any wait handle, we can remove the
code that handles that case.
2013-05-06 09:31:36 -07:00
Sara Golemon 16e0a5bdf0 Fix race condition in ext/sockets/tests
This time the race condition comes from binding sockets!
2013-05-06 09:31:36 -07:00
Edwin Smith d15e609333 Revert "Do copying with the AttachLiteral constructors."
Revert "Explicit CopyString, remove (const char*) constructors."
2013-05-06 09:31:26 -07:00
Sean Cannella 9bc56bdeb5 use byte instruction for boolean binary ops in hopt
- use byte instead of qword instructions to perform binary operations on two booleans
2013-05-06 09:09:05 -07:00
Sara Golemon 3858cae7e8 Generated ext_hhvm files live in CMakeFiles not next to what they're wrapping 2013-05-03 12:02:55 -07:00
Sara Golemon cf076e8972 Link dl, pthread, and glog into gen-ext-hhvm, gen-infotabs, and folly 2013-05-02 16:21:02 -07:00
Mark Williams 57e10942ba Undo systemlib change
Put systemlib in the repo again, and use it for repo-authoritative builds
2013-05-02 10:14:16 -07:00
Andrei Alexandrescu 11151fe1ea Eliminate unnecessary and unawesome instances of dynamic_cast<HphpArray*>
There are two dynamic_cast<HphpArray*> instances in bytecode.cpp that cause code to fail when using other types of arrays. However, the necessity of those casts seems to have disappeared in the meantime because simply removing them compiles and runs. I have ran full 'fbmake runtests' after removing the first cast (all passed). Then I removed the second cast (in lexical order) and ran the tests again. This time test/zend/good/ext-hash/hash_file_basic.php failed, but when I ran it again in separation it passed.
2013-05-02 10:14:16 -07:00
Jan Oravec 88687ba6f7 Add support for external thread events
Add support for external thread events.

See asio_external_thread_event.h for details about usage.

This is the first version that compiled, the code was not executed even
once, but wanted to get it out early to unblock @hannesr. Thus the [RFC]
flag.

My next step is to implement asio-compatible equivalent of
fb_call_user_func_async() that will make it possible to easily test the
new functonality by simulating async stuff with sleep(), etc. on the PHP
side.

There are 2 major mostly lockless synchronization points that needs
careful review:

- queue of ready external thread events (asio_session.{cpp.h})
- shutdown cleanup (asio_external_thread_event.{cpp,h})
2013-05-02 10:14:16 -07:00
Jan Oravec 8f3e34430c Remove deprecated WaitableWaitHandle::getStackTrace()
WaitableWaitHandle::getStackTrace() is not used anymore. The stack trace
is computed on the PHP side using the provided reflection API.
2013-05-02 10:13:57 -07:00
Mark Williams b38422cfa1 Close the file handle after finding a section
The code to find an elf section in the binary left the
binary open.
2013-05-02 10:13:39 -07:00
Mark Williams 30075b74c9 Reduce repo contention issues
If there were multiple processes (or threads) trying to write to
the repo, we were spending a lot of time in raw_spin_lock, resulting
in almost no forward progress. The new test case runs in about 8
seconds on my dev server, with a debug build, but didnt complete in
20 minutes when using the current release build of hhvm.

I also removed the 20 thread limit on the test runner, which
drops the time for SlowJit from about 1:45 to 1:30, and should
no longer cause repo-contention issues.
2013-05-02 10:13:38 -07:00
Drew Paroski a3620e7758 Remove hphp_get_iterator and related dead code
This code is no longer used, let's get rid of it.
2013-05-02 10:13:38 -07:00
Owen Yamauchi e6a3807f23 Support generating ext_hhvm files with ARM ABI
ARM's convention for returning bigger-than-a-register types is
different; there's a register reserved for the purpose of passing the
return-value pointer. On x64, it just gets added as a hidden first
parameter.
2013-05-01 23:01:13 -07:00
Jordan DeLong eec5d43e4c Remove legacy makefiles (take 2)
We need to leave runtime/tmp for TestServer and TestDebugger,
but they don't actually use the old makefiles.
2013-05-01 21:00:49 -07:00
aravind a5102a5d5e Implement FCallArray in IR 2013-05-01 21:00:49 -07:00
Sara Golemon 32b76a7a3c Fix race condition in test/.../ext-hash/hash_file_(basic|error).php
Fix pushed upstream already
2013-05-01 21:00:48 -07:00
Paul Tarjan c11c56d9f9 fix dupe filename
./tools/import_zend_test.py  -z /tmp/php-5.4.13/ -o filesize_variation3
2013-05-01 21:00:48 -07:00
Jordan DeLong effe6d71f3 Omit stack overflow checks on leaf functions
I did an experiment turning off all stack checks, and it
looks like it does cost something.  This seemed like an easy way to
turn it off some of the time, but maybe we should resurrect the SEGV
handler.
2013-05-01 21:00:48 -07:00
Drew Paroski 9a804f6463 Implement Set 2013-05-01 21:00:47 -07:00
Jordan DeLong 0a4bb765e0 Move ConvFooToBool selection to Simplifier
This is stateless---and it's possible the second
simplification pass may be able to perform more of it if operand types
change somehow (wishful thinking?).
2013-05-01 21:00:47 -07:00
Jordan DeLong 1e1166d4d4 Remove genAssertStk/genCastStk and move their optimizations to Simplifier
The elimination of these is stateless, so it's going to
simplifier (along with getStackValue).  Other stack functions are
still here until I move EvalStack to tracebuilder.
2013-05-01 21:00:47 -07:00
Jordan DeLong c3619ecd7b Remove some easy remaining TraceBuilder::genFoo functions
This diff should have nothing very interesting in it.
2013-05-01 21:00:46 -07:00
Jordan DeLong d936b8e120 Document TraceBuilder/HhbcTranslator/Simplifier @override-unit-failures
Adds comments explaining the role of each of these modules.
The comments explain the roles as I am planning to make them, not as
they actually are, so they are currently partially lies.  (I will move
EvalStack into TraceBuilder, and get the remaining "dubious" gen
routines out to HhbcTranslator on top of this diff.)
2013-05-01 21:00:46 -07:00
Jordan DeLong 0f752932cf Move gen{Guard,Assert}Loc logic to updateTrackedEffects/preOptimize
GuardLoc drops into preOptimize.  genAssertLoc did two things
based on a bool---one of which needed logic in preOptimize, and the
other which implied something for updateTrackedEffects (and was
handled in hhbctranslator).  Also removes genLdAssertedLoc---it's not
an instruction; I considered an emitLdAssertedLoc but since this is
only used in a few places (less than a LdIncRefLoc would be) it seemed
fine to just flatten.
2013-05-01 21:00:39 -07:00
Jordan DeLong 3e93f5404e Remove genDecRef from TraceBuilder
Replace with a preOptimizeDecRef.  Also caught a pseudo-issue
where we relied on the isRefCounted short-circuit for correctness (we
called genDecRef on Type::Cls).  That short-circuit is duplicated in
simplifier, and is stateless, so let's leave it there.  Remove some
dead code about BoxedCells and replace it with a comment in
ir.specification based on a conversation with @bsimmers.

(This is on top of all the other related diffs.)
2013-05-01 21:00:39 -07:00
Jordan DeLong a2eec97e62 Rename TraceBuilder::genDefConst to cns()
Closer to the same instruction creation api in each.
2013-05-01 21:00:32 -07:00
Jordan DeLong 0903f92a76 Fix arithmetic op uses of type paramters, get rid of gen{Sub,Mul,...}
These guys were determining their output type with DParam,
even though the output type was a function of the input types.  Fixed
this and then get rid of the genFoo wrappers.  Move binArithResultType
out of Type.  OpMod didn't need a type parameter.
2013-05-01 21:00:32 -07:00
Jordan DeLong 406eb59593 Simplifier gets gen()/cns(), replace genDefConst with cns outside tracebuilder
Also removes simplifier's genDef{Bool,Dbl,Int}.
2013-05-01 21:00:31 -07:00
Jordan DeLong 68cfa7c17e TraceBuilder and VectorTranslator get forwarding gen() helpers
s/m_tb(->|\.)gen/gen/
2013-05-01 20:59:46 -07:00
Jordan DeLong 858731971a Remove many of the genFoo functions from tracebuilder
Removes most of the wrappers in favor of gen(). Does two
cases that actually had logic by adding a new "preOptimize" pass where
TraceBuilder can use tracked state to modify instructions before they
go to the simplifier.
2013-05-01 20:59:46 -07:00
bsimmers 66f23c5c06 Kill alwaysLowMem
We're hitting the assert in some jobs (see task) and it's not
a measureable win.
2013-05-01 20:59:45 -07:00
jdelong b26e59a920 Inline the outer functions for continuations with no arguments
We store a bunch of data into an ActRec on the stack, then
call a php-level function that calls a C++ function to copy it into an
ActRec on the heap.  This should hopefully be a little better.
2013-05-01 20:59:45 -07:00
Jan Oravec 102c37cdcb Remove deprecated asio_* methods
Remove unused deprecated methods:

- asio_enter_context()
- asio_exit_context()
- asio_get_current()
2013-05-01 20:59:45 -07:00
Sara Golemon 38f9fab773 Fix __HALT_COMPILER() support
Actually halt the compiler, and set __COMPILER_HALT_OFFSET__ constant
2013-05-01 20:59:44 -07:00
Drew Paroski 6a2c5150ed "trait implements" syntax 2013-05-01 20:59:44 -07:00
Andrei Alexandrescu e434a1872d Simplify test output 2013-05-01 20:59:37 -07:00
Mark Williams 6cb23e0f56 Don't cse LdCns
Because in php, constants aren't.
2013-05-01 14:47:14 -07:00
Mark Williams 17a8693f65 Don't crash reversing empty Vectors
In a new, empty vector start and end are null.
2013-05-01 14:47:14 -07:00
Sara Golemon 2aa8ed4814 Sync parser generator with upstream 2013-05-01 14:47:13 -07:00
Sara Golemon 85cd3df409 Require CMake version 2.8.5 or higher
Support for hand-written assembly was "experimental" in older
versions and would select the wrong compiler yielding a build
failure.

2.8.5 and later do the right thing.
2013-04-30 10:20:41 -07:00
Mark Williams 6f4b1c76a8 Fix issue with call_user_func_array and by-ref params
We can't box a non-ref value for a ref param because
we could be modifying an array with refCount != 1.

zend warns, skips the call and returns null. For now, this
makes us warn, but do the call (without modifying the array).

A file scope flag controls whether to skip the call or not,
and should be changed (and eliminated) once all our tests pass.

With the flag turned on, we still dont match zend's behavior,
because its happy to go ahead and call the function with no
warning in the case of a literal array parameter
(cuf('foo', array(1))), even though it warns and skips it when
the array is in a variable ($a=array(1); cuf('foo', $a)).
2013-04-30 09:58:57 -07:00
Jordan DeLong b3ae38b6c0 A few minor tweaks about HPHP_HOME
I think everything should work without it now.
2013-04-30 09:58:56 -07:00
Owen Yamauchi a57ae0488a Generate the parser at build time, part one
Update a number of things to make optionally generating the parser at
build time possible.  @sgolemon will add the OSS pieces of this in a
separate commit.
2013-04-30 09:57:57 -07:00
Dario Russi 36326b4de0 rename getReturnTypehintText() to getReturnTypeText() to be consistent with the new API that drops the 'hint' part in the method name
Simple renaming of method for consistency reasons
2013-04-30 09:27:08 -07:00
Guilherme Ottoni 7900cb18d1 Move translation counters after tracelet guards
With HHIR, I noticed they were being emitted before the guards.
Instead of having the insertion logic check for first marker, add an
IR instruction for incrementing the counter.

Also, got rid of firstMarkerSeen flag.

And also fixed lint warnings while here.
2013-04-30 09:27:07 -07:00
Owen Yamauchi 79b8d27a80 Add a bit of graceful error handling to C++ IDL code
Instead of failing obtusely, do some checking of the JSON schema so we
can produce useful error messages. This doesn't strictly check
everything that could be checked, but it will catch the most common
errors (i.e. the ones I discovered while making this change originally).
2013-04-30 09:27:07 -07:00
Jordan DeLong d5bfa422b8 Do assertOperandTypes on each instruction after each pass
Check for broken invariants.
2013-04-30 09:27:07 -07:00
Jordan DeLong 8fb0544504 Fix a bug in HHIR's emitParent
We actually grabbed the parent of the parent.  This means
things like parent::foo() were skipping the immediate parent.
2013-04-30 09:27:07 -07:00
Edwin Smith 12c676bc8b Litstr must die, episode V.
Removed the litstr overloads of Array::rvalAt, rvalAtRef, lval,
lvalPtr, lvalAt, and set.  The main one left to do is operator[].

Fixed a bug in f_get_html_translation_table() where we were copying
the null terminator of what should be a one-character string, thus
creating a two-character string with s[1] == 0.  (cc @jdelong)

In class Extension, store a String for the name instead of
const char*.  cc @sgolemon
2013-04-30 09:27:06 -07:00
mwilliams db271750c3 Allocate registers for the main trace first
Linearscan placed the exit traces immediately after
the branch to them. This meant that they could cause spills in
the main trace. This diff re-orders things so that they come last,
but saves the state at each exit point, and restores it before
allocating each exit trace.

I've not yet dealt with the "live across native calls" case, so
this does cause more registers to fall into that category. I'll
tackle that in a follow up diff. But this already seems to be on the
good side of neutral.
2013-04-30 09:27:06 -07:00
Mark Williams 825ba1200f Don't issue MissingAbstractMethodImpl warnings unless WholeProgram
Local linting just looks at the files that were changed,
so we dont always see the implementation of an abstract method.
Disable the warning in that case. We'll still catch it when
we do whole program linting later.
2013-04-30 09:27:06 -07:00
Jordan DeLong e7999d34bc Keep simplifyCall stateless
Read the stack out of the instruction instead of out of
TraceBuilder's current stack pointer.
2013-04-30 09:27:05 -07:00
Paul Tarjan 51151a407f import non-predictable number tests
I couldn't handle these until we had ##.expectf## support. Now we do.
2013-04-30 09:27:05 -07:00
Paul Tarjan 5ca1e9b337 make test runner work in open source repo
Our contributors should be able to run the tests.
2013-04-30 09:27:05 -07:00
Drew Paroski 86a616a220 Add KeyedTraversable interface 2013-04-30 09:27:05 -07:00
Drew Paroski aa8b2afc7d Make new reflection API instead of changing getTypehintText()
A bunch of tests were failing because the behavior of getTypehintText()
changed. Instead of changing how getTypehintText() behaves, let's just
introduce a new reflection API, and then tests and application code can
be changed to use the new API later.
2013-04-30 09:27:04 -07:00
Mark Williams f48de277d4 array_values dropped references
It should preserve them. This was breaking pass-by-reference
via ReflectionFunction::invokeArgs.
2013-04-30 09:27:04 -07:00
bsimmers 603d50c7b1 Shorten SSATmp::getInstruction, SSATmp::getType, IRInstruction::getOpcode
The function names were too damn long.
2013-04-30 09:27:04 -07:00
Paul Tarjan 90e7a30404 fix shared test name
This test was imported WITHOUT hard-coded output. Meaning it was compared to zend. It so happened that I had cleaned my repo after any runs of ##TestExt## so the file they both created (and sometimes didn't clean up) didn't exist. So that is the output I recorded.

@mwilliams do you think you intended for the file to exist? It wasn't in the repo.

With this diff I'm using a unique filename so it doesn't matter if ##TestExt## hasn't cleaned up perfectly.
2013-04-30 09:27:04 -07:00
Edwin Smith b7cc57a8db Explicit CopyString, remove (const char*) constructors.
This gets rid of the (litstr) StringData and StackStringData
constructors, but keeps String(litstr).  Also rename all
the instances of AttachLiteral to CopyString, since they now
mean the same thing.
2013-04-30 09:27:03 -07:00
bsimmers 8760794304 hhir punting to interp by default, master version
Let's do this. It's already on in the current rc; this is
mostly to get another test run on current master.
2013-04-30 09:27:03 -07:00
Dario Russi 6e510c2081 fix reflection parameter problem where type and type hint were made to collide. Separated the two...
ReflectoinParamenter was fetching both type and type hint from the same field. That created an incompatible change with existing code and broke the mocking framework. Separated the type and type hint field to contain the possible different values.
2013-04-30 09:27:03 -07:00
Paul Tarjan 5aede8cba8 fix segfault
Don't assume we are in a function.
2013-04-30 09:27:02 -07:00
Rasmus Lerdorf 441c137dcb Implement PHP 5.4's short array syntax
We have traits and some other PHP 5.4'isms why not the short array syntax as well?
2013-04-26 13:28:39 -07:00
jdelong b6c11c0fc0 Add SpillStack's sources to the instruction type assertions @override-unit-failures
Check the types on its sources.
2013-04-26 12:59:48 -07:00
jdelong 9749e6bd54 Initial support for inlining small functions
Sets up the translator analyze pass to create a Tracelet for
the callee at every statically-known FCall.  If the callee has an
appropriate shape (in this diff, it must be a function consisting of
"return $this->foo" for a declared property), we can inline it in
HHIR.  Restructures the IR relating to frames some so we can eliminate
the stores relating to ActRec in this simple case (see the comments in
dce.cpp and hhbctranslator.cpp for details).  Includes partial support
for inlining callees with locals, but it's disabled for now because
they will keep the frame live.
2013-04-26 12:59:48 -07:00
Mark Williams 3b8b611627 Fix a missing SpillStack
LdClsPropAddr can throw if it doesn't have a target.
2013-04-26 12:59:47 -07:00
bsimmers 41f2b117ee Revert "Fix varios ext/hash algorithms"
This was causing an unexplainable perf regression.
Revert it for now pending deeper analysis.
2013-04-26 09:31:13 -07:00
Bert Maher cea48118bf Create a FramePtr type for the IR and use it where appropriate
Even though a stack pointer and a frame pointer are pretty
similar things, it's nice to be able to tell just by looking at the
type whether we're dealing with something on the eval stack or
something at a frame pointer offset.  Adding this type makes it clear
where things need to change to modify the ABI.
2013-04-26 09:31:07 -07:00
bsimmers 1c2a22180d Don't check surprise flags in onFunctionExit
It's causing unwinding problems.
2013-04-26 09:31:00 -07:00
Paul Tarjan 2da286594d fix race in mkdir 2013-04-26 09:30:54 -07:00
Paul Tarjan fe7efe7192 fix race condition in SplFileInfo_getInode_basic
These failed once on @smith's diff and I think it was from them both running at the same time.

I'm not really sure why the others changed their path, but that is the original zend file.
It shouldn't matter as it is a error line that will be set to whatever we print out if the test passes.

Done with:

  tools/import_zend_test.py -z /tmp/php-5.4.13/ -o SplFileInfo_get
2013-04-26 09:30:15 -07:00
Paul Tarjan 52305fda58 read all of stdin 2013-04-26 09:29:56 -07:00
smith a73e674aea Litstr must die, episode IV.
Removed Array::remove(litstr).  Grouped the other litstr overloads
together and reimplemented each one in terms of the CStrRef overload.
2013-04-26 09:29:53 -07:00
Edwin Smith 410a105184 Do copying with the AttachLiteral constructors.
And, remove the IsLiteral string kind.  This removes the hazard of
creating a string whose data is freed before the string.  Callsites
passing in a literal should use StaticString.  Everything else
can use CopyString or AttachString.
2013-04-26 09:29:48 -07:00
Sara Golemon 4c4d11304a Add a rule for generating the parser from util/parser/hphp.y 2013-04-25 19:40:25 -07:00
Sara Golemon 065ac81ee8 Hunt down pthread instead of just assuming that we'll find it. 2013-04-25 16:42:05 -07:00
Sara Golemon b10a27e178 Generate ext_hhvm/infotabs files on the fly rather than as pre-builds 2013-04-25 15:33:05 -07:00
Sara Golemon c2d720b1a6 Clean up some leftover pieces of unused stuff 2013-04-25 15:13:59 -07:00
Mark Williams 72ae1b9f85 Get rid of o_isClass 2013-04-25 11:34:23 -07:00
Mark Williams 6dc8c10bae Fix types for builtins
Unknown types should generally be Type::Variant, except
in the case of parameters, where they should be Type::Any.

The difference is that coercing to type Any doesnt affect the
existing type, where coercing to type Variant forces it to
type Variant.
2013-04-25 11:34:22 -07:00
Jordan DeLong 1bcfc357fd Rename equals/hash to cseEquals/cseHash and assert canCSE() 2013-04-25 11:34:22 -07:00
Jordan DeLong 55ba7a9279 Adjust an expression I forgot from earlier code review 2013-04-25 11:34:22 -07:00
Herman Venter 1bf6c5d588 Keep the hphpd alive and responsive after the run command.
When debugging a script using a local VM (i.e. when there is no remote VM),
the cleanup actions performed by the run command caused the debugger client
to shut down as well. Since this seems to be intentional, processing of the
run command now restarts the debugger client and proxy. Also, following a
ctrl-C, the m_lastLocFilter field must be cleared, otherwise an empty endless
loop cannot be broken into for a second time.
2013-04-25 11:34:21 -07:00
Edwin Smith f29ee5314d Remove String::operator const char*().
Too many ways to shoot self in foot with this gem.
2013-04-25 11:34:21 -07:00
Paul Tarjan 991fef8842 import zend standard tests
Lots of the win32 ones work for creating but not removing.
2013-04-25 11:34:20 -07:00
Paul Tarjan 7bf0846868 fix flakey gztests
I noticed on one of my diffs that one of these tests failed and I think it is because they were all sharing a file.
2013-04-25 11:34:12 -07:00
Paul Tarjan 650171dc17 factor out a function
I meant to do this when I wrote it. Less scope leakage.
2013-04-25 00:50:12 -07:00
Mike Magruder 0e88603b5d Merge DebuggerProxyVM into DebuggerProxy, InterruptSiteVM into InterruptSite
The separation between these classes was a vestige of days gone by. Combined them. I ran into issue with having the proxy split up in particular when working on stepping, so doing this now as a separate diff to keep things cleaner.
2013-04-25 00:50:12 -07:00
Mike Magruder 7a928e7689 Consolidate client/server functions in debugger commands
Cleaned up some of the superfluous variations of onServer*()/onClient*() in the debugger commands. The separation was a leftover of the days when we had the VM and the compiler. The entire DebuggerCommand interface, what's public/protected/private, etc. could use a serious cleanup, but I'm not going that far now. I mostly wanted to clean this up to make some other work we need to do server-side less complicated.
2013-04-25 00:50:12 -07:00
Jordan DeLong cb57a50c01 Allow temporary ExtraData objects in instruction generation
Brett said the inability to pass temporaries here made him
not a huge fan of extra data, so this adds that.  Also simplifies the
int,SSATmp** case a bit by packaging them into a pair (this makes it a
bit less subtle to understand why go2 terminates, which was going to
get way more complicated after Tail becomes Tail&& if I wanted to keep
it that way, so I didn't).
2013-04-25 00:50:12 -07:00
Jordan DeLong ca902ff1e8 Fix an updateTrackedEffects bug for InterpOne
InterpOne was not properly tracking its effects on the stack
offset.  The return-type-means-an-extra-push thing was compensated for
in both hhbctranslator and tracebuilder.
2013-04-25 00:50:11 -07:00
Paul Tarjan a4fc1c7bbd import zend spl tests
Lots of these tests spewed files
2013-04-25 00:50:11 -07:00
Sara Golemon dd8d33fc7f Silence undefined property error when functions are defined without flags 2013-04-25 00:50:04 -07:00
Owen Yamauchi 781359b60d Rewrite gen_ext_hhvm and gen_infotabs in C++
This is a near-straight translation of gen_ext_hhvm.php into C++. The
main goal of this change is to break the bootstrap cycle in the build
process: we have to run PHP scripts to build our PHP interpreter. This
isn't so bad for us internally, but in the open-source build, it's
philosophically lame to depend on an external PHP interpreter (i.e.
Zend) to build HHVM. To get around this, we have to check in the
generated ext_hhvm files: no good.

There's nothing particularly sophisticated in this program; it's just a
bunch of grunt work. I took the opportunity to make a few improvements
to the generated code -- there was some int-width confusion, and a bunch of
duplicated code to transfer return values to the right place.
2013-04-25 00:50:04 -07:00
Paul Tarjan 8cf864ef14 import zend pdo_sqlite tests 2013-04-25 00:50:04 -07:00
Paul Tarjan 49b97d2aad import zend pdo_mysql tests
I did some minor surgery to the import script to always copy in the php files. This is because zend has ##config.phpt## files which, as their name doens't reveal, aren't really tests but instead are config files.

After all that, the tests still didn't work because I'm not running mysql on localhost.
2013-04-25 00:50:03 -07:00
Paul Tarjan 61b57050a4 import zend mysql tests 2013-04-25 00:50:03 -07:00
Paul Tarjan 42ad0071ab import zend xmlwriter tests
a few spews
2013-04-25 00:50:03 -07:00
Paul Tarjan ef61c8dd30 import zend sqlite3 tests 2013-04-25 00:50:03 -07:00
Paul Tarjan c7466541f8 import zend pgsql tests
We don't pass a single one because of

  Undefined function: pg_connect
2013-04-25 00:50:02 -07:00
Paul Tarjan a9861a4c53 read tests from stdin
Sadly when I do the full zend import the command line gets too big.
2013-04-25 00:50:02 -07:00
Paul Tarjan ab4929477c fully quality paths
I was pretty inconsistent in here. It is better to be explicit.

To keep myself honest, I did:

  rm -r test/zend; tools/import_zend_test.py -z /tmp/php-5.4.13/

Of the changed files:

* type_hinting_005a.php was missed in the original import
* closure_033.php someone changed by hand before
* date and posix tests now pass magically
* bug43703 too

The rest are whitespace updates
2013-04-25 00:50:02 -07:00
Paul Tarjan 7d3eb74b6a print out hphp command too 2013-04-25 00:50:02 -07:00
Paul Tarjan 2589e072fb mark 3 tests as segfaulting 2013-04-25 00:50:01 -07:00
Keith Adams 98483c74d6 Lift a lot of stuff out of HPHP::VM.
This is a partial step towards merging the HPHP::VM namespace
up into its parent. To keep it reviewable/mergeable I'm not doing
everything at once here, but most of the code I've touched seems
improved. I've drawn an invisible line around the jit, Unit and
its cohort (Class, Func, PreClass, etc.); we'll get back to them
soon.
2013-04-25 00:50:01 -07:00
Sara Golemon d5ea8ff20f Add PHP 5.5's array_column() function
http://wiki.php.net/rfc/array_column
2013-04-25 00:50:00 -07:00
Sara Golemon 182995353f Fix varios ext/hash algorithms
Added sha224 algo (derivative of sha256)
Added fnv132, fnv1a32, fnv164, fnv1a64 algos
Fixed tiger* finalization (endianess was backwards)

I fixed the endianness of tiger*,* and added Zend's
unit tests, but I forgot to update these tests.
2013-04-25 00:50:00 -07:00
Owen Yamauchi 05b6e5be7d Rename lexer source and add generator rule 2013-04-25 00:50:00 -07:00
Mike Magruder a41a8a74f0 Remove the Jump command from hphpd.
Hphpd's Jump command has been fundamentally broken for a long time. It was originally implemented to run the byte code in a modified way which didn't make state changes, and wait for the destination offset to be reached. We lost the ability to do that long ago, and the implementation of this command has atrophied since. As it stands now, if you're lucky it might act like "run until", which is the opposite of what it is documented to do.

I've removed the command entirely. Fixing it is a very large effort which we might consider some time in the future.
2013-04-25 00:49:59 -07:00
Paul Tarjan 2980d466f2 import zend zlib tests 2013-04-25 00:49:59 -07:00
Paul Tarjan 5646a4ee78 import zend posix tests 2013-04-25 00:49:59 -07:00
Paul Tarjan c3901f775f import zend xmlreader tests 2013-04-25 00:49:59 -07:00
Paul Tarjan fd1c19c741 import zend soap tests 2013-04-25 00:49:58 -07:00
Erling Ellingsen 48e0cf8479 Don't send URL in redirect body
If you put a CR in the redirect URL, the response splitting protection refuses to send the Location header, and the body is rendered in the browser; instant xss. It would not surprise me if some browsers ignore the Location header for less obviously broken URLs, so let's just remove the URL entirely.
2013-04-25 00:49:58 -07:00
Paul Tarjan 51807939d1 import zend xml tests 2013-04-25 00:49:58 -07:00
Paul Tarjan bd5e0b1f7b import zend simplexml tests 2013-04-25 00:49:58 -07:00
Paul Tarjan 82cc511666 import zend session tests 2013-04-25 00:49:57 -07:00
Paul Tarjan 155a38ea1d import zend sockets tests 2013-04-25 00:49:57 -07:00
Paul Tarjan acf7de7e64 import zend mcrypt tests 2013-04-25 00:49:57 -07:00
Paul Tarjan f5ef2a06f0 import zend mbstring tests 2013-04-25 00:49:57 -07:00
Paul Tarjan 648d190d9a import zend ldap tests 2013-04-25 00:49:56 -07:00
Paul Tarjan 99310da27c import zend openssl tests 2013-04-25 00:49:56 -07:00
Paul Tarjan 70befd44fb import zend intl tests 2013-04-25 00:49:56 -07:00
Paul Tarjan cb0fea957d import zend gd tests
They didn't create any extra files so it was straightforward
2013-04-25 00:49:56 -07:00
Paul Tarjan f5f8d4ec40 import zend exif tests
It seems we emit an error on unknown file and they don't.
2013-04-25 00:49:56 -07:00
Jordan DeLong 158d32fab5 Make cseKill tolerate temps from non-cseable instructions
If you have a killsSources instruction where one of the
sources comes from a non-CSEable instruction that has extra data, this
currently aborts because it tries to call hash() for the extra data
but can't.
2013-04-25 00:49:55 -07:00
Mark Williams a2981eaf25 Embed systemlib.php into hhvm
Also, since its always present, remove the special case
code for adding systemlib to a RepoAuthoritative repo,
and clean up all the magic variables for finding systemlib.

If HHVM_SYSTEMLIB is set, and the file exists, it will be
used as systemlib, otherwise, the embedded one will be used.
2013-04-25 00:49:50 -07:00
Jordan DeLong c39252e9f9 Determine hphp_home in test/run via __DIR__
The system() here was echoing to stdout.
2013-04-24 22:32:36 -07:00
Sean Cannella 54efa29d5f Fix off-by-one in multi-line function call traces
Fixes off-by-one in line number reporting in multi-line function calls
2013-04-24 22:32:36 -07:00
Paul Tarjan 3f880f93e2 fix bz2 race
Since we run these in parallel then there is a bad ordering of these where they eat eachother's files.
2013-04-24 22:32:28 -07:00
Mark Williams 3e75f5b7e4 Fix issue with Unit::merge
A recently introduced bug could cause classes and
interfaces to be silently dropped in repo-authoritative mode.
2013-04-24 17:13:58 -07:00
Mark Williams d0e1d78cd5 Implement Cns in hhir
Thats it
2013-04-24 17:13:58 -07:00
Sean Cannella 87f9e8cd1c add mod_apache_log %I support to HHVM webserver
- added support for %I (bytes received / request size with headers) in HHVM access logs
2013-04-24 17:13:58 -07:00
Herman Venter 1d6efdcbb4 Rename DebuggerProxy::send, DebuggerClient::send and DebuggerClient::recv
I found myself getting confused, thinking that proxy->send(cmd) sends a command to the proxy, when in fact it causes the proxy to send the command to the client. These are now named sendToClient, sendToServer and recvFromServer so that future readers (including my future self) will not make this mistake again.
2013-04-24 17:13:58 -07:00
Paul Tarjan ede4f96d4e fix pcre whitespace 2013-04-24 17:13:54 -07:00
Mark Williams 0526e973c5 Fix literal string to int/double conversion under hhir
The simplifier would convert strictly-integer strings to their
integer equivalent, and all other strings to zero. This meant
that eg "1.1" became zero, as did "1x". Normally, such strings
are converted at the ast level, so it was hard to expose the bug,
but eg test/quick/cnvInt.php would fail if you turned off
JitEnableRenameFunctions (and its turned off in repo mode, so the
repo mode test was failing).

The same issue was present in ConvStrToDbl, but there was a bug in
StringData::isNumeric causing it to return true for a weakly-numeric string,
where its contract is to return false (and it did return false for an
equivalent, non-static string). Once I fixed that bug, I had to fix the
bug in ConvStrToDbl.
2013-04-24 12:42:45 -07:00
Paul Tarjan e0b5db348a import zend pdo tests 2013-04-24 12:42:45 -07:00
Paul Tarjan 71113aef61 import zend pcre tests 2013-04-24 12:42:44 -07:00
Paul Tarjan 4710a5538a import zend pcntl tests 2013-04-24 12:42:44 -07:00
Paul Tarjan 042ea354d0 import zend imap tests 2013-04-24 12:42:44 -07:00
Edwin Smith f0394e1d0d Lint fixes for type_array.h
Just tackling one file at a time.
2013-04-23 12:59:00 -07:00
Paul Tarjan 8d15db5860 import zend libxml tests
only 1 good test? *sigh*
2013-04-23 12:58:59 -07:00
Paul Tarjan 44e8962b85 import zend json tests 2013-04-23 12:58:59 -07:00
Paul Tarjan f9b83dc6af import zend iconv tests 2013-04-23 12:58:59 -07:00
Paul Tarjan dba18c78ed mark oci8 unsupported
these tests require an oracle server be set-up? That's pretty rough... We'll tackle these later when they become the lowest hanging fruit.
2013-04-23 12:58:59 -07:00
Paul Tarjan ad74e1f391 import zend hash tests
not bad. >50%
2013-04-23 12:58:59 -07:00
Paul Tarjan 306686be70 No need to support opcache for test parity 2013-04-23 12:58:15 -07:00
smith c646a30002 Litstr must die, episode III.
Many callsites of Array.set(litstr, ...)
2013-04-23 12:57:40 -07:00
Herman Venter 71a6e2b628 Add TRACE calls to debugger code.
Added a new trace flag and added TRACE calls to all functions in files living directly in the hphp/runtime/eval/debugger directory
2013-04-23 09:52:58 -07:00
Jordan DeLong 094a729549 Kneecap an ext_spl test that had too many filesystem things going on
It was failing intermittently in contbuild and in different
fbcode checkouts.
2013-04-23 09:52:58 -07:00
Jordan DeLong 469afe85d9 Remove old HHVM_GC code
This was left over from GC-related experiments, and isn't
needed now.
2013-04-23 09:52:58 -07:00
smith 46f11e95d0 Remove bool key overloads from Array smart pointer
They were dead code.  Removed weakRemove() methods, also dead code.
More importantly, foo("something") binds to foo(bool) if there
is no foo(litstr), so this avoids accidentally calling the wrong
overload as I'm ripping out litstr overloads.
2013-04-23 09:52:58 -07:00
smith 37e49ba6e4 Remove dead ConnectionInit class
thats it
2013-04-23 09:52:57 -07:00
Mike Magruder ac9665e148 Remove old vestiges of frame injection.
Nuke a little dead code that is leftovers of the old frame injection goo.
2013-04-23 09:52:57 -07:00
Paul Tarjan 017b6f231b spill the inputs of CreateCl onto the stack
I did this for the IR but didn't do it for the JIT :(
2013-04-23 09:52:57 -07:00
Mike Magruder 76db66ec82 Add comments to some of the debugger code to aid in understanding it more clearly, plus minor code cleanup.
Add a lot of comments to the debugger based on my current understanding of it. These may change in the future as we learn more, but they're helpful right now.

Also moved a few small things around in the code to clarify their purpose or scope. I.e., making a few things private, renaming a few functions, etc. No real logic changes, though. Also minor dead code removal. Also a few lint errors.
2013-04-23 09:52:57 -07:00
Mark Williams 9a8b0d3ba4 Respect ignoreRedefinition in repo mode
In repo mode, we kept the builtin. Keep the user function
instead.
2013-04-23 09:52:57 -07:00
Mark Williams b8c78a9141 Get rid of some hphpiCompat brokenness
These were strictly to avoid people writing code that
worked under hhvm, but then fataled under hphpi. Since hphpi is
long gone, its time we removed it (no danger of breaking real code
since anything that worked before continues to work - and hphp
was already "doing the right thing" because it flattened traits).
2013-04-22 14:43:52 -07:00
Mark Williams a2e46efe38 Make sure we raise a warning in repo mode
Repo mode can skip undefined variable warnings,
if they're known to be uninit at compile time, and eliminate
expressions whose only side effect might be to raise a
diagnostic.
2013-04-22 14:43:52 -07:00
bsimmers fa0a201dde Revert "name anonymous continuations as Class::Method$continuation" 2013-04-22 14:43:52 -07:00
Mark Williams e0995af8dc Turn off optimizations in repo mode for some tests
They don't seem worth fixing.
2013-04-22 14:43:52 -07:00
mwilliams 0a70a77f42 Fix an issue with exit/include/etc
Various unary operators have arbitrary effects. Dont assume we
know anything about locals when we see one.

Fix an expect for differences in line numbers.

Prevent a use of an undefined constant from being optimized away.
2013-04-22 14:43:51 -07:00
Paul Tarjan eca135cb31 delete most PHP in C++
Sadly I can't get TestDebugger, TestServer, TestExt, QuickTests, or TestPerformance as they are all unsuported by verify. Someday.
2013-04-22 14:43:51 -07:00
Paul Tarjan 53d1db1669 revert over-zealous simplification
I was trying to simplify code flow by removing things with tainted variables. I got too carried away and thought tainted wait handles were the same.
goodcatch
@override-unit-failures
2013-04-22 14:43:51 -07:00
Jan Oravec e42d42d35e Rename AsioContext members to be camelCase
All m_* object members in ext_asio are camelCase, except in AsioContext.
Rename them. Also, m_queue_ready became m_runnableQueue, as with the
introduction of async functions a new abstract RunnableWaitHandle will
be introduced.
2013-04-22 14:43:51 -07:00
Jordan DeLong f650635e0b Define __STDC_FORMAT_MACROS in build configuration
Avoids some header order dependencies.
2013-04-22 14:43:51 -07:00
Jordan DeLong a70b1bf8f7 Ad few more lint fixes under runtime/vm/translator 2013-04-22 14:43:50 -07:00
Jordan DeLong 80dece2b6b Fix a (smart heap) leak in Variant's move constructor @override-unit-failures
When unboxing a ref, the Variant move constructor is leaking
the RefData.
2013-04-22 14:43:50 -07:00
Jordan DeLong a2df3fcf9a Fix lint errors about catching exceptions by value 2013-04-22 14:43:50 -07:00
Jordan DeLong e287f5e5ff Fix some mismatched include guards 2013-04-22 14:43:50 -07:00
Jordan DeLong 7449c3afea Remove util/lfu_table.h
This is unused.
2013-04-22 14:43:50 -07:00
Jordan DeLong 3af00dc1b1 Fix various lint warnings stemming from hphp/util 2013-04-22 14:43:49 -07:00
Jordan DeLong 24cb23f21b More fixing lint: various conversion constructors in compiler/
Left one implicit, but it's arguable.  Inspected manually.
2013-04-22 14:43:49 -07:00
Jordan DeLong 3db2140e3e Fix some cpplint errors about illegal symbols
Various perling.
2013-04-22 14:43:49 -07:00
Edwin Smith 22d70113c7 hphp/src is now hphp/hphp
That's it
2013-04-22 14:43:48 -07:00
Jordan DeLong 04f4f27eba Fix stack offset tracking in emitPrint, caught by zend test
The emitPrint function failed to pop the cell when it decided
to nop out the print.  This led to the stack being off by one when we
got to the RetC in this test.
2013-04-22 14:43:48 -07:00
Mark Williams 2a759db5e6 Fix reflection for default values that were optimized
If a default value is optimized from a class constant,
to the value of the class constant, then reflection needs to
be able to get the text of the original class constant.
Fortunately hphp tags that onto the replacement expression for
just this reason. Lets use it in the emitter.
2013-04-22 14:43:48 -07:00
Mark Williams b28254c8f2 Fix a crash if an exception is thrown in a constructor's surprise check
The unwinder assumed that if the actrec's constructor flag
was set, then there must be a $this. But the $this is cleared during
the return sequence.
2013-04-22 14:43:48 -07:00
mwilliams fb214b9655 Better dynamic constant support in repo mode
A constant defined in a function/method should be treated as
dynamic.
A class constant with a dynamic initializer should evaluate to
the value of its initializer at the time the constant was first
seen; so the optimization should be all or nothing - either
turn the class constant into a scalar, or leave it in its original
form.
2013-04-22 14:43:48 -07:00
Paul Tarjan 91db25c8e1 use run_test_other.sh for 5 C++ test suites
This will make things less error prone. If we fork early in the makefile instead of sharing some infra then changes to the PHP-based test infra won't break c++ tests.

While I was there, I tried to fix the weird order that some tests had
the suite first and some had the set first. It got hard since D773384 hasn't
landed yet. When we do that, then I'll cleanup that stuff.
2013-04-22 14:43:47 -07:00
Paul Tarjan 72dffc0aef kill TestPerformance
deadcode
I think perflab is a better tool
@override-unit-failures
2013-04-22 14:43:47 -07:00
ptarjan 387369de96 import random crap zend files
Many zend tests require files which aren't in their .phpt files. We need these extraneous files if we want these tests to pass.

Zend isn't nearly as clean as I would hope. Here is how I did it:

* Move EVERYTHING from the directories to test/zend/all
* run the tests thre with all the random crapy files
* move things in the whitelist to good
* move everything else to bad

@override-unit-failures
2013-04-22 14:43:47 -07:00
Paul Tarjan 25b842d845 fix 3 zend tests for whitespace problems
Rebase ate my whitespace :(

I added mutliple ##-o## support to easily support fixing some tests like this:

  ./tools/import_zend_test.py -z /tmp/php-5.4.13/ -o ctype_space_variation1.php -o ctype_xdigit_variation4.php -o bug33957.php
2013-04-22 14:43:47 -07:00
Sara Golemon 82489e1fd1 Make generators always-enabled
Zend supports generators now, so it's not
really HipHop specific syntax anymore
2013-04-22 14:43:46 -07:00
Jordan DeLong 347aad68c8 Add a few things to hphp/test/.gitignore 2013-04-22 14:43:46 -07:00
Owen Yamauchi bc47e4aa91 Rebuild parser, move test into test/slow
@override-unit-failures

D774978 was checked in with a broken test. New tests go in test/slow
now. The test was broken because @drussi apparently didn't rebuild the
parser after his last diff update (changing 's' to 't').
2013-04-22 14:43:46 -07:00
Paul Tarjan 6f932592ea fix some lint
I tried to remove the namespace thing but that rabbit hole went too deep. When I hit ##OPCODES## I stopped.
2013-04-22 14:43:35 -07:00
Paul Tarjan 5decac3716 add zend shortcut
This should be here for completeness. And so @jdelong can easily fix them :)
2013-04-22 14:43:35 -07:00
Paul Tarjan be05d0d87a style changes
I'll do the nitpicks, sorry @jdelong.
2013-04-22 14:43:21 -07:00
Mark Williams 983a59a000 Add hphp_opts file for types
fixes test/quick/parse_type_not_typedef.php
2013-04-22 14:18:05 -07:00
Mark Williams 29ff6382e2 Prevent an equality check from being optimized away
We were depending on a side effect of the string conversion
2013-04-22 14:18:05 -07:00
Mark Williams 0b7e8d1251 Check accessibility before replacing static props with their value
If a static property is provably not modified, and it has
a literal initializer, it is optimized away at translation time.
We should check that its accessible before doing that.
2013-04-22 14:18:05 -07:00
Mark Williams 2294a515f6 Fix poly-torture to avoid order of eval issues
Normally, hhvm will translate

  echo "x $x";

as

  echo "x ".$x;

Which fully evaluates the rhs, then starts to output it.

hphp will transform it to

  echo "x ", $x;

Which avoids the concat, but outputs "x " before evaluating $x. hphp wont
perform the transformation if there are obvious side effects, but it will
treat a simple variable as having no side effects - even though it may
be uninitialized.

Im just fixing the test by performing the transformation manually. I don't
think anyone cares whether the $x undefined notice appears before or after
the "x ".
2013-04-22 14:18:05 -07:00
Owen Yamauchi 008387c504 Minor tweaks to the IDL
While rewriting gen_ext_hhvm in C++ I discovered these little
anomalies: the "return" field of a function has to exist, and has to be
a dictionary.

I'm also removing the specific class name of hphp_create_continuation as
per the discussion, and removing the support for parsing
types like that.
2013-04-19 22:53:58 -07:00
Jordan DeLong f3c2ab5d77 Fix runtests to make it workable for contbuild
It wasn't actually decoding test names anymore due to paths
changing; also several slow tests failed when run from the root (which
is where contbuild is going to run them).  Added stuff to make
$HPHP_HOME unnecessary for runtests (contbuild wont have it set), and
fixed a use of $GLOBALS in hphp/test/run to be more php-idiomatic.
2013-04-19 22:53:31 -07:00
ptarjan 4c77061e3f import curl tests
Not very good coverage here, but @sgolemon predicted that.
2013-04-19 17:13:24 -07:00
Mark Williams 39df1a8b20 Free the VarEnv the correct way
detach, rather than destroy.
2013-04-19 17:13:23 -07:00
Mark Williams a988bdb73e Fix a couple of include tests in repo mode
One just needed to have the file included in the repo.
One was getting the wrong return value (true vs 1).
2013-04-19 17:13:23 -07:00
ptarjan a4334f1870 import ext-date tests
We aren't doing so well on these. Some are ##false## vs ##NULL## but others are ##DateInterval## which sucks to not have.
2013-04-19 16:42:20 -07:00
ptarjan 3932003411 import ctype tests
All pass, yay.
2013-04-19 16:42:12 -07:00
ptarjan b719d1947d blacklist all zend tests
Instead of having to remember which -o params to pass, I'll just put everything as blacklisted that we havn't import.
2013-04-19 16:42:02 -07:00
ptarjan 70a6d9cde9 import bz2 tests
I had to edit ##bzopen## so that it handles file handles or else the test makes files called ##Resource #5## in the current directory.

The big problem with the broken tests is we return ##NULL## on too few args and Zend returns ##false##. I want to get a feel for other extensions before changing this.

I also imported ALL the files in the directory since the ##.phpt## files overflow.
2013-04-19 16:41:53 -07:00
ptarjan fb9b8c1552 support 2 more sections
Support two more section keys and only print the message when using /all
2013-04-19 16:41:46 -07:00
Mark Williams 95251c59cf Fix fbcufa.php in repo mode
just need to ensure its found at compile time
2013-04-19 16:41:41 -07:00
ptarjan e36e75fa5f remove duplicate tests
I imported these with my old zend importer. Now that we have zend/good, these are duplicated.

There are 3 zend tests left:

* zend_closure_005.php
* zend_closure_020.php
* zend_indirect_method_call_005.php

Which we've hand-edited to be similar to zend but not exactly the same. I'm going to leave them for now.
2013-04-19 16:41:29 -07:00
ptarjan 0edeb118db fix zend importer
I broke this during the test refactor. And now a few more tests pass, yay.
2013-04-19 16:41:12 -07:00
jdelong 4be0858c63 Add 'convenience' name aliases to test/run
This was the main feature in my wrapper script.  Allows
running tests by more terse names.
2013-04-19 12:21:56 -07:00
mwilliams 6f223125a5 Prevent more optimizations in repo mode
"$unused_local = UndefinedConstant;" was being optimized away, so
we didnt get a warning for the constant. return it instead.

  $unused_local = new Object;
  return;

became

  new Object;
  return;

This affected the (unspecified) order of destruction of $this
vs $unused_local. Since we're specifically trying to test that
we dont crash when a local generates a backtrace after $this
has been destroyed, force the variable to be used.
2013-04-19 12:21:56 -07:00
mwilliams ad30d03b8c Fix order of evaluation for unused binary operators
eg

  (new X) == (new X);

Was converted to something like:

  (new X);
  (new X);

Which calls the destructor for the first X before constructing the second.

I tried a fix where we used an ExpressionList with ListKindLeft, which
would preserve both expressions until after both objects are created;
but that ends up calling the second object's destructor first. Thats
much better; its not clear to me that there's any guarantee about which
object's destructor is called first when they both go out of scope at
the same point; but currently hhvm and zend seem to aggree, so Im
going with a solution that preserves the left-to-right order.
2013-04-19 12:21:55 -07:00
aravind 2137af76be Fix bug in shuffleArgs
This diff fixes a bug in shuffleArgs when there
are three register arguments in a cycle, and one
of them needs a zero extend.

Assume the shuffle that needs to be performed is
rdi -> rsi, rsi -> rdx, rdx -> rdi. doRegMoves()
determines the sequence of moves to be:

  xchg rdx, rsi
  xchg rsi, rdi

Assume also that the second dest reg (rsi) needs a zero extend.
The current implementatin will spit out the code
sequence:

  xchg   %rdx, %rsi
  movzbl %sil, %esi
  xchg   %rsi, %rdi
  movzbl %sil, $esi

Basically, the problem is that if a move sequence uses
two xchg's for a cycle of three registers, we should not perform
the zero extending (and address-lea) till both the exchanges are done.
2013-04-19 12:21:55 -07:00
mwilliams 0f9e81197b Prevent some repo mode optimizations
Since its seen the whole program, it optimizes class_exists
to false if there's no definition anywhere.
Replace local variables with globals so that assignments can't
be optimized away (since we're gathering coverage information).
2013-04-19 12:21:55 -07:00
aravind 97766b0367 fix for ConvToString
When we do CastString on an object, the ConvObjToStr helper
may throw if it does not have a __toString() function.
When spilling the stack before calling the helper,
we must push back the popped object.

Also convObjToString helper should not decref its object if the conversion failed.
2013-04-19 12:21:55 -07:00
drussi 6e8178da16 expose type annotation to reflection including generics, function types and tuples
This is intended so reflection can be used (via getTypehintText and getReturnTypehintText) to regenerate code the user annotated with types. Essentially using reflection to intrispect code in order to generate type safe
(hack safe) code. That is particularly important for the tools that do dependency injection. The runtime should be oblivious to the change as the rich type annotation is currently only stored for the sake of reflection. For
functions the values are in the shared portion which is cold and should also take care of traits.
2013-04-19 12:21:55 -07:00
mwilliams bdddf9f01d Arrays as class constants should be a parse time fatal
We were detecting this in the emitter, which is too
late, because the definition could be optimized out by then
2013-04-19 12:21:55 -07:00
jdelong cbbc3a4906 Make $HPHP_HOME optional for hphp/test/run, change default bin_root()
If it's not set, let's just use git rev-parse.  If you don't
have FBMAKE_BIN_ROOT in your env, use _bin/ by default (for the last
thing you built) instead of <root>/bin/, which is only around for
perflab compat.  Made the help a little more to my liking (and not
ruin syntax highlighting in emacs).
2013-04-19 12:21:55 -07:00
ptarjan cabe5aa8e7 escape glob
The current dir might have ##php## files in it.
2013-04-19 12:21:55 -07:00
ptarjan a8fa0afffc kill dead param
I'm digging in here, and saw relative is always false.
2013-04-19 12:21:55 -07:00
Owen Yamauchi 34fdda13e1 Convert the IDL to JSON
It's data, not code.

My primary motivation for doing this is to make the IDL accessible from
languages that aren't PHP. (This, in turn, is motivated by a desire to
eliminate PHP scripts from the build process.)
2013-04-18 16:44:16 -07:00
bsimmers 5d1c69b048 Revert Generator changes 2013-04-18 14:24:56 -07:00
ptarjan 04cc89a235 Remove one level of indirecation
Instead of the python script calling the php script which calls the perl script, now the python script returns a command to run.

I was thinking about chaging the jenkins output to mention the php script intead of the makefile target, but sadly there are a few things that aren't scripts and are just makefile targets so it was too much work and I just stopped here.
2013-04-18 13:55:38 -07:00
hermanv 5e6cce4db5 Conversions in IR
Rolls up all previous diffs into a single diff and uses the CALL_OPCODE macro.
2013-04-18 13:55:38 -07:00
mwilliams c68de03df2 Don't fold invalid string operations at compile time
It turns out the String::rvalAt and String::set don't raise
warnings on invalid offsets, so check explicitly before using them.
2013-04-18 13:55:38 -07:00
bsimmers d94be65db1 Disable test/quick/serialize.php 2013-04-18 13:55:38 -07:00
bertrand 6a93844442 Add support for safe (un)serialization using (un)serialize()
The unserialization of random objects may be dangerous because the destructor of the object will be called when the unserialized objects are out of scope. However, the person who wrote the class may not be aware of the danger of unserialization. Therefore, we would like to require every users of the unserialize() to provide a whitelist of the class names that are authorized to be unserialized so that we can make sure the object is safe to be unserialized.

Add a parameter 'class_whitelist' to unserialize() function to determine whether to raise warnings for unsafe unserialization. If the class to be unserialized is not an instance of Serilizable or not in the whitelist, warnings will be raised. For the detailed reason why we need this, please see http://fburl.com/SafeSerializable for more information.

Add a parameter 'all_classes_enabled' to allow  those hphp functions that need to unserialize any class. For example, fb_call_user_func_async() will need to serialize and nserialize the given parameters.
2013-04-18 13:54:55 -07:00
ptarjan 2e5d5fbb15 fix SlowRepo tests
Yay, back to the glory days of having repo tests.

The problem was that we weren't being smart about ##__DIR__.'/some/string'## during the compile step. Now we are.
2013-04-18 12:19:35 -07:00
ptarjan b6f60e2f2c fix runtests 2013-04-18 12:19:35 -07:00
aravind 1fddbbebc9 Cleanup for debugging IR under gdb
update block range on each IR instruction
add CodeGenerator::print()
2013-04-18 12:19:35 -07:00
jdelong 74202fab80 Remove drawCFG and tcdump trace module
We have tc-print now, and I don't think people use this
anymore.
2013-04-18 12:19:35 -07:00
mwilliams d39bf0bcfe Method names should not be coerced to string
Zend fatals if the type is not string, where hphp would
coerce to string. In RepoAuthoritative mode, this meant that
scalar expressions would be converted to strings at bytecode
emission time, bypassing the fatal (or, in most cases, resulting
in a different fatal).
2013-04-18 12:19:35 -07:00
mwilliams 6df0912bc0 Get rid of baseStrOff
It was unnecessary book keeping, and caused us to differ
from zend's behavior
2013-04-18 12:19:35 -07:00
ptarjan 6eef35d561 nicer message on failure
smith asked for this. Prints out the exact options to run it by hand. If it is in repo mode, it uses the already built repo. Otherwise it just runs the file. If you are only running 1 test, it does the FILENAME sustitution for you. I thought it would get pretty ugly if I printed out that line for every test.
2013-04-18 12:19:06 -07:00
smith 89f5f70e42 Litstr must die, episode II. 2013-04-18 12:19:06 -07:00
jdelong 89e34e12e6 Disable memelim
It's causing issues with the vector translator.
2013-04-18 12:19:06 -07:00
ptarjan 61973ed25c fix 1798 output
It seems calling ##fileinfo->getFilename()## twice outputs the empty string the second time. Document that in the test for now and look at it later.
2013-04-18 12:19:06 -07:00
ptarjan a974f84f15 try to fix machine dependant problems again
I think these are dependant on relative directories. Seeing if this helps.
2013-04-18 12:19:06 -07:00
jdelong 2e3445bf38 Add a tvIsPlausible assertion in vectortranslator @override-unit-failures
We were hitting an assertion due to a type error in a vector
translation far downstream.  Assert up here to keep it closer to the
TC.
2013-04-18 12:19:06 -07:00
mwilliams c203d5a772 Dont box by-reference params that would warn/fatal
If we know at emission time that an argument is by reference, we box
it, and use FPassV with a NopOut meta tag. But that bypasses the
mechanism for warning/fataling when passing a Cell. So skip the
optimization in those cases.

Fixes two more QuickRepo tests:
test/quick/FPassC-2.php
test/quick/FPassC.php
2013-04-18 12:19:06 -07:00
mwilliams 27b4b0b53c Don't profile 86ctor
Its an implementation detail, and we may or may not end up
calling it.
2013-04-18 12:19:05 -07:00
mwilliams 5f9df0e7c6 Rework constants to use the target cache exclusively
Make the targetcache the one true home for constants,
so we dont need to (also) insert them all into
VMExecutionContext::m_constants (which is now gone).

By also making "non-volatile" constants persistent, we save
initializing most of them at all in RepoAuthoritative mode.
2013-04-18 12:19:05 -07:00
smith 98466ea3fd Litstr must die, episode I.
Converted lots of callsites to StaticString, removed a few
dead overloaded litstr functions.
2013-04-17 10:12:48 -07:00
Paul Saab 1097d2dcb5 Count active threads in PageletServer
We were not counting the active running threads in PageletServer
which made /check-pl-load on the admin port return zero always.
2013-04-17 10:12:48 -07:00
jdelong ee3628c272 Relax an assert slightly after the change to unbox keys in-TC 2013-04-17 10:12:48 -07:00
jdelong 17344c4b5a Don't spillStack as much for CGetM
I forgot to test wantPropSpecializedWarnings for simple
CGetMs that don't have an hphpc-infered type.
2013-04-17 10:12:48 -07:00
bsimmers be6394b828 Disable HhbcTranslator::emitMod 2013-04-17 10:12:47 -07:00
mikemag 17731f2252 Let destructors run after main for Zend tests.
Added EnableObjDestructCall=true to the config for zend tests.
2013-04-17 10:12:47 -07:00
mwilliams b5f81ab942 Constant propagation was too aggressive
it assumed that $a = 5; echo $a; would echo 5, which isn't
true if $a is the last reference to an object whose destructor
can get hold of $a.
2013-04-17 10:12:47 -07:00
ptarjan 6e899255c6 move .php files to .inc in test/quick that aren't tests
Instead of having a blacklist on name, how about we use a different file extension for included files? Many PHP installs do this for files that are in the document root but shouldn't be served.
@override-unit-failures
2013-04-17 10:12:47 -07:00
bsimmers 4fd5886617 Unbox vector helper keys in translated code
Instead of creating a template specialization of each helper
that unboxes the key, do the unboxing in the TC when applicable. This
will shift a few instructions from helpers to the TC but greatly
reduces the number of helpers needed by the vector translator.
2013-04-17 10:12:47 -07:00
bsimmers 6b552c7e77 Don't type-specialize helpers for uncommon vector operations
Many of these helpers are fairly infrequently called so it
doesn't make sense to have a different version of each one for the
different key types. This will slightly increase instructions but
should help icache performance.
2013-04-17 10:12:46 -07:00
mwilliams d8f5055660 Fix Repo config settings for test/quick
Also clean up some cruft in test/config.hdf
2013-04-17 10:12:46 -07:00
ptarjan c3699bb8e3 fix slow tests
These tests have machine dependant things in them. Copy Zend and change the machine things to %s.
@override-unit-failures
2013-04-17 10:12:46 -07:00
ptarjan 4c2b9a3bc2 rewrite test running in php
It turned out to be more lines but feels a bit more maintainable. Thoughts? I personally would like python more here but I think @kma likes php for scripting.
2013-04-17 10:12:46 -07:00
mikemag 5240dae6a9 Add a new option to control args in backtraces
Add Eval.EnableArgsInBacktraces, which defaults to !Repo.Authoritative. This allows us to test what happens when backtraces keep references to function arguments even when testing in authoritative mode. Modified the test harness to set this to true when using Repo.Authoritative.
2013-04-17 10:12:46 -07:00
bmaurer ea2b1a06ec Use bstrcaseeq in isame
bstrcaseeq is a bit less complex and should be faster for this case.
2013-04-17 10:12:45 -07:00
aravind 4d0ab6d254 Null check for colorize 2013-04-17 10:12:45 -07:00
jdelong cff9360510 Fix a bug in CreateCl, combine helper calls and use precoloring
The CreateCl translation dereferenced its targetcache handle
at compile time instead of in the TC, so we could get "class
undefined" errors if the targetcache slot in the thread that jitted it
didn't happen to have that closure defined.  Fix that, combine the two
helper calls, and use nativecalls so we get register precoloring.
2013-04-17 10:12:45 -07:00
mwilliams 4842f4ee1d Flatten fast path in GetNamedEntity
While investigating why gcc-4.7.1 is slower than gcc-4.6.2,
I noticed that under 4.6.2 the tbb code was being inlined into
Unit::GetNamedEntity, but under 4.7.1 it wasn't. Perf showed that
the inclusive time for GetNamedEntity was about .4% higher under
gcc-4.7.1.

Meanwhile, after various code changes, gcc-4.6.2 is no longer
inlining the tbb code either. Playing with the inlining options,
I wasnt able to get either version of gcc to inline it anymore,
but using __attribute__((__flatten__)) works for both. But that
also causes a bunch of other, slow-path code to be inlined, so
split it into a hot and a cold function, and flatten the hot
function.

Perf shows about a .2% win for Unit::GetNamedEntiry under gcc-4.6.2
2013-04-17 10:12:45 -07:00
smith 88f2ec2fb9 Remove ArrayData litstr overloads
Some were dead.  Refactored the rest to use the CStrRef overload
instead, while still supporting litstr in the Array, ArrayInit, and
Variant apis.
2013-04-17 10:12:44 -07:00
ptarjan db6f5f3d54 s/QuickTests/TestUnit/g
I looked at all the tests, and they seem to be unit tests for small parts of hphp.

They were run at the start of every TestExt test too, so I changed that so they are really just their own test now.
2013-04-17 10:12:39 -07:00
jdelong abc9170968 Fix typedefs/shapes for whole program optimization
Needed a few cases for KindOfTypedefStatement,
EnableExperimentalHipHopSyntax, and passing it through to the scanner.
2013-04-17 09:51:40 -07:00
mwilliams 62315ccb15 Fix crash in linting
Redeclared functions in non-whole-program analyze mode caused
an assertion failure.

Test Plan:
  % cat bug.php
  <?php
  if (isset($g)) {
    function f($x, $y) {}
  } else {
    function f($x) {}
  }
  f($x);
  % hphp -vWholeProgram=false -t analyze bug.php
2013-04-17 09:51:40 -07:00
chip fe9373358e Add function to get the async status for a mysql connection
This will allow for php code to better verify the async state
of the mysql connection and aid in debugging.  This diff adds
mysql_async_status as well as associated constants.
2013-04-17 09:51:40 -07:00
ptarjan 9db58086ac rename all the tests
After the "Great Test Refactor of 2013" these names didn't make sense.

After this diff, we now have 3 suites:

* Quick (old vm)
* Slow (old TestCodeRun)
* Zend

I like that Quick tests aren't in sub-suites and the Slow tests are. So that is a good litmus tests of what to put where.

I left all the old Makefile rules. I'll blow them up in a few weeks.

This diff is based on a simple unreviewable diff of

  $ mv test/vm test/quick
  $ mv test/tcr test/slow
2013-04-17 09:51:29 -07:00
ptarjan fca7a90240 Rename test directories
These names don't make sense now that we run both suites the same
way.
2013-04-17 09:08:16 -07:00
ptarjan 503f75d08b Rename test directories
These names don't make sense now that we run both suites the same
way.
2013-04-17 09:06:51 -07:00
ptarjan f42dbb6ddf delete repo file before trying
I've noticed that sometimes it won't rebuild the repo. Delete it just to make sure.
2013-04-17 08:55:07 -07:00
ptarjan ea27bcf156 rename /tools/run_verify.sh to /test/run
I'd like to make people use the script for running tests. With all the different options, the matrix of Makefile rules is getting pretty big. And with all the makefile magic, they aren't very discoverable what is runable.

The old name was pretty bad for tab completion. Since we have a dedicated test directory, why not put the script there? I'm not in-love with `run` but there are no other `r` files there so it is nice for tab completion.
2013-04-17 08:55:07 -07:00
ptarjan e35c2971c2 start running TCR tests with verify
I went a bit crazy and supported all the quick and zend tests in the same format. Or do you think we should normalize the other way? Or are there better names? I think if you like this, I should move the "vm" directory to "quick" and the TectCodeRun to "slow" directory or something so we put tests into nicer suites.
2013-04-17 08:54:58 -07:00
mikemag 602b1bd64f Ensure C++ exceptions eventually propagate out of destructors.
This diff addresses what we called "step 1" in the task: simply ensure that any C++ exceptions that escape a destructor get rethrown and can continue to propagate naturally. The exception is remembered on the thread, and rethrown when we check for surprises later. If multiple destructors let C++ exceptions escape the last one to escape will be the one rethrown at the next surprise check.

This also ensures that C++ exceptions prevent more PHP code from running, by omitting calls to __destruct methods as we unwind the stack.

Finally, this also enables surprise checks for OnFunctionExit unless we're unwinding, in which case surprises remain unchecked so they can propagate later.

This is different than Zend's behavior, where destructors do run as fatals unwind.
2013-04-17 08:54:58 -07:00
mikemag b677c776df Fix bug in heredoc processing
My recent change to now/heredoc processing resulted in variables in heredocs mistakenly being tacked onto the end of the previous line in the output. This tends not to be a problem when emitting things that get parsed by something else, like emitting PHP. But it's noticable when emitting raw text.
2013-04-17 08:54:58 -07:00
smith cc0ef7c456 Change copy-on-write protocol to always return valid pointers
Streamline the array access methods by always returning an array
pointer instead of a new pointer or null.  Callsites compare
(new != old) to detect escalation, rather than (new != null).
2013-04-15 13:03:16 -07:00
smith 8cd07ce9f6 Rename RuntimeType/DynLocation::isVariant() -> isRef() 2013-04-15 13:03:16 -07:00
jdelong 2ef635db28 Optional syntax-highlighted HHIR dumps
It's enabled if the HPHP_TRACE_FILE is "/dev/stdout" or
"/dev/stderr" and also isatty(), or you can set HPHP_TRACE_TTY in your
environment to override it (e.g. if you like to pass to less -R).
2013-04-15 13:03:16 -07:00
ptarjan 4bd0cdb05e Support repo mode in run_verify.sh 2013-04-15 13:03:03 -07:00
ptarjan dd36937f94 new opcode CreateCl
This is the bottleneck for closure perf. Instead of all the code in the prologue, it turned out the expensive thing about closures was constructing them. This bypasses all the roundabout copying involved with __construct and makes a new opcode to do the same thing.
2013-04-15 13:01:49 -07:00
ottoni da37a0ae8f interpOne instructions that fail the HHBC->HHIR translation
This diff adds full support for doing general interpOnes in HHIR.
Whenever a bytecode instruction fails (punts) in the HHBC->HHIR
translation, the NormalizedInstruction is marked with an 'interp' flag
and the HHIR translation for the whole tracelet is retried.  This
forces an InterpOne of such instruction, preventing HHIR from
attempting to translate it again, which then allows the HHBC->HHIR
translation to make further progress.  If another instruction in the
sequence punts again, the process is repeat and so on.
2013-04-15 13:01:49 -07:00
Owen Yamauchi b3d14bfdda ifdef out rdtsc in hotprofiler
I'm punting on this for now. I'm afraid of violating assumptions about
how the clock behind this interface works (and we do very specific stuff
like calculating CPU clock speed), so I don't want to try to replace it.
We'll revisit when we need to do serious profiling on ARM; we'll
definitely notice that this functionality is missing when we try to use
it.
2013-04-15 13:01:48 -07:00
ptarjan eb401ae91f move TestCodeRun tests from strings to files
I changed the ##run_verify.sh## script to recursivly search for a ##config.hdf## file and use that one. This allows us to easiy customize the options for each suite.

I converted the 6 different runtime options we supported to symlinks of ##.opts## files to the option that the test wants. If I was smarter I would then convert these to ##config.hdf## if the whole suite wanted the same options, but I'll save that for later cleanup if we want it.

I moved the config files around a bit. `test/cli.hdf` became the default `test/config.hdf`. `test/config.hdf` became `test/tcr/config.hdf`. `test/zend/config.hdf` is also now an empty file so it doesn't inherit `test/config.hdf`.

I'll handle the Repo part of the tests in the next diff. Then the next one after that will delete all the cpp code and Makefile targets and force you to just use ##tools/run_verify.sh## which I think we should rename ##test/run## or something easy.
2013-04-15 12:56:31 -07:00
Owen Yamauchi 743f51e107 Separate handwritten assembly helpers into a .S file
This feels like a cleaner approach. It separates code that's
arch-specific by nature, lets us avoid all the ugly quote marks and \n
sequences, and lets your editor do real syntax highlighting of asm.
2013-04-12 13:07:23 -07:00
ptarjan 0038b76a58 kill TAINTED code
While I was working on the TestCodeRun refactor I found two tests about Tainted code. I looked into it and coulnd't get HHVM to compile with TAINTED=1. Then I checked and none of the extension functions we exposed about tainting were used in WWW. Scratching my head I asked, @srenfro and @jdelong, who  thought it was dead. So I killed this zombie.
2013-04-12 12:04:04 -07:00
bsimmers b8ae94e039 Implement FPushCuf* in hhir
This handles almost all the cases tx64 does. It takes a slow
exit when a Class or Func that was around at translation time doesn't
exist at runtime, which never happens in prod (as of right now).
2013-04-12 12:04:03 -07:00
kma 197305cc45 HHIR mod. 2013-04-12 12:03:57 -07:00
bsimmers 0dd21ce600 Disabled non-refcounted locals optimization
It's still flaky, and I'm hitting asserts related to it on
trunk right now.
2013-04-12 11:22:45 -07:00
jdelong d432f19ae1 Allocate unit bytecode and metadata in a read-only memory region
Only in RepoAuthoritative mode, where units can't be
deallocated.  I have a semi-reproducable bug where a unit's m_bc
region is getting corrupted (only occasionally in perflab).
Presumably moving it out of the malloc'd heap will make the bug
corrupt something else, so this probably doesn't really help much, but
it seemed like having a separate region for some cold, read-only,
process-lifetime metadata might make sense.
2013-04-12 11:22:45 -07:00
jdelong 9e7de4a990 Use hphpc-provided property types in CGetM prediction
We still need to check that the types aren't null, but we can
continue traces with a side-exit guard.
2013-04-12 11:22:45 -07:00
jdelong 264500f5f9 Add a few traces in annotation.cpp 2013-04-12 11:22:45 -07:00
bsimmers 547a45231d Shut down if we lose a LightProcess child
This should only happen if there's a bug in our code and the
child process crashes, or if one gets killed by the OOM killer. In
either case, it's probably not safe for the parent process to continue
uninterrupted, so shut down.
2013-04-12 11:22:44 -07:00
kma 4f8bcc9f6c Remove HPHP_LIB as a place to find systemlib.php 2013-04-12 11:22:44 -07:00
ptarjan 36b9a96335 stop prefixing test to TEST_PATH
It is good design to not repeat things that are redundant,
but this keeps anoying me that I can't tab complete this.
no-one should be used to the syntax yet so now is the time to change it.
2013-04-12 11:22:44 -07:00
ptarjan c19b117f6b use sample dir for TCR
I made a sample directory with a file, a symlink, a dir, a recursive symlink and an empty file. Hopefully that is enough edge cases.

I tried to find all the places that used weird files and ##test## in TCR and used this dir instead.
2013-04-11 14:34:56 -07:00
ptarjan 568f06d05d remove conflict markers
Summary:
If I try to split these into non-strings, I get a commit hook error.

To get rid of them I did this:

  %s/=======*/------------------------/g
2013-04-11 14:34:14 -07:00
ptarjan 9b1dc0f963 create .diff file even for .expectf
I'm having a tough time debugging the ##.expectf## tests because I don't have an easy diff. This is a poor man's one unless someone else is aware of a nice regex debugging thing.
2013-04-11 14:34:14 -07:00
bertrand b31744c3da Optimize NewObj when no constructor is needed
Tx64 has this optimized helper path for object creation when the
default 86ctor construction is used.  Ported this to HHIR.
2013-04-11 14:34:14 -07:00
Sara Golemon 5323725b0c Kill off .inc files
Import data from ClassInfo (sourced from class_map) instead
2013-04-11 13:54:52 -07:00
seanc 0840deb71a Use name to be consistent with Zend in backtraces
Generators should specify function names as the name instead of the
full name for consistency with Zend 5.5 (and more importantly because
this breaks PHPUnit), this was exposed by the backtrace removal of
file and line info
2013-04-11 12:13:43 -07:00
bsimmers 284d8f144d Implement StaticLocInit in hhir
This is almost the same as tx64's implementation, with one
substantial difference: the targetcache slots hold RefData* instead of
TypedValue*. This is ok because cache handles aren't shared between
translations. I also had to rework some code in dce to handle
consuming a reference through a phi node.
2013-04-11 12:13:43 -07:00
bertrand a2ffc03900 Always inline opPre
opPre is marked as inline, but our current gcc version isn't
actually inlining it anywhere.  I find that surprising, because it
seems like a no-brainer: the function is small and the code gets
better when inlined (e.g., it gets rid of stores to reference params).
This diff makes the text very slightly bigger but should have good
effects on locality within the helpers.
2013-04-11 12:13:42 -07:00
mwilliams 26cf67d974 Fix interface1.php's expected output
Somewhere in the .filter consolidation and cleanup,
the bit that stripped the function name was removed. Add it
back.
2013-04-11 12:13:42 -07:00
mwilliams dd56c6821f Util::string_printf should do printf style argument checking
I made a mistake adding persistent target cache to
TranslatorX64::getUsage that would have been caught.

Also adds the persistent target cache stat.
2013-04-11 11:03:49 -07:00
bertrand 7de123db40 Only compile one instance of member_operations functions
Functions declared as "static inline" in member_operations.h
end up getting compiled into each translation unit that includes that
header, leading to a lot of duplicated code.  Changing them to just
"inline" causes only instance to be used globally, which seems likely
to be friendlier to icache.
2013-04-11 11:03:49 -07:00
ptarjan 4dfde31584 remove support for .exp
I left in a message to read the README, but I don't know if people will see it mixed into the output.
2013-04-11 10:58:54 -07:00
ptarjan ac1d69902e name anonymous continuations as Class::Method$continuation
As a user, this often annoyed me that I couldn't get any debugging info
out of the name and then @ahupp asked for it.

I didn't really know what to name closure ones as the name is done at
emission time. So I went with ##{closure}##. I'm not sure how I feel
about that since it will be uncorrelated with the emitted name.

While I was in there, I deleted a lot of unused code.

I'm totally open to other names and ideas.
2013-04-11 10:58:54 -07:00
ptarjan 25b9556349 kill dead code 2013-04-11 10:52:54 -07:00
ptarjan 8b3bb26b22 kill default.filter and switch everything to .expect or .expectf 2013-04-11 10:52:48 -07:00
ptarjan 27dc48a6bf kill all .filter files
.expectf can do everything these do in a more readable way.
2013-04-11 10:52:18 -07:00
ptarjan 7a6aeba983 Support zend's test formats
Zend tests have 3 possible sections for test output. EXPECT, EXPECTF, and EXPECTREGEX. I think we should do the exact same thing. The .filter thing is difficult to write tests that have random numbers involved and the PHP community should already be familiar with the EXPECTF format strings.

Migration plan:

  * Kill all .filter files
  * Rename all .exp to .expect
  * Stop supporting .exp

I'm basically planning on suporting all of zend's sections as file extensions. Basically, if they have a section ##FOO## we will have a file ##test.php.foo## (where we need them).

I changed the import script to use our json encoding instead of deciphering what happened from the ##.diff## files (since not everything will have a ##.diff## file now)

We have 50 ##.filter## tests. I'll go convert them to expectf and see if they are easier to read.
2013-04-11 10:38:43 -07:00
jdelong 00380e6ba7 Don't generate RaiseUndefProp in RepoAuthoritative mode
This avoids a SpillStack for simple CGetMs.  Gated under a
flag that defaults to true.
2013-04-11 10:38:10 -07:00
andrewparoski e63a9b3d63 Remove a few more uses of ClassInfo 2013-04-11 10:38:10 -07:00
hermanv 874dee78fd Split ConvToInt into subopcodes specialized by argument type.
We now have ConvArrToInt, ConvDblToInt, ConvObjToInt, ConvStrToInt and ConvGenToInt. This allows these opcodes to have separate flags.
2013-04-11 10:38:10 -07:00
bsimmers 882ef43fbb Disable TestExtMysql 2013-04-09 15:33:09 -07:00
Sara Golemon 9381ab39e7 Improve idl.php generator
Output constants and class implementations in .cpp file
Include base.php via __DIR__ rather than cwd for calling from outside hphp/idl
2013-04-09 15:33:09 -07:00
andrewparoski ecdd701952 Clean up ArrayData APIs for mutable iteration
Replaces the awkward getFullPos() and setFullPos() methods with a more
intuitive advanceFullPos() method. This refactoring also reduces the number
of virtual calls made when doing mutable iteration on an array.
2013-04-09 15:33:09 -07:00
jdelong 486ca81213 Use hphpc-inferred object property types to avoid KindOfUninit checks
The frontend appears to alread pessimize its prediction of
object property types whenever an UnsetContext might affect a given
property.  We can use this to avoid checking for KindOfUninit when
doing specialized prop gets in the vectortranslator.  This is
hopefully going to be worth more than it sounds, because it will let
us avoid a spillStack, which is a use of the frame and will prevent an
inlined getter from removing the ActRec (unless we implement some kind
of sinking for frames).
2013-04-09 15:32:17 -07:00
jdelong 37f5f9cb5a Some comments about use of rVmFp and rVmSp in codegen
We shouldn't be using these registers directly nearly as much
as was appropriate in tx64.
2013-04-09 15:32:17 -07:00
jdelong 9dc66f2f40 Fix an exception safety issue for undefined properties in vectortranslator
I think the only case where we currently don't spillstack as
part of a vector translation is CGetM of a defined property.  However,
this can still raise exceptions in the unlikely case of an unset
property.  For now, just spill before any vector translation---a
follow up diff relaxes this to not do it in cases where we know the
property can't be undefined.  Presumably later we'll push the
spillstacks into the unlikely paths for these translations (or put
them in unwind handlers)---currently we can't handle control flow
where the join point has a different stack.
2013-04-09 15:32:17 -07:00
hermanv 090bc82fa2 Specialized code generation for more of the ConvXxxToDbl instructions.
Rather than using just two general purpose helpers, there are now some specialized helpers and more inline code. Also, the flags in ir.h are now more accurate.
2013-04-09 15:32:17 -07:00
mwilliams e350aa5461 Prevent elimination of stores to generator params
After some recent cleanup to generators, local analysis was
able to remove some stores that it shouldnt have done, because
it didnt take account of the fact that the locals were
generator parameters.
2013-04-09 15:32:17 -07:00
bsimmers 15d4e7d7fe Move a couple zend tests back to bad 2013-04-09 15:32:17 -07:00
jdelong 96d22113c9 RFC: Pass the assembler to use to unlikelyIfBlock
In tx64, a common bug (for me) was to accidentally type "a."
instead of "astubs." when writing code inside an UnlikelyIfBlock,
since your fingers get used to the former.  More generally, it seems
like we should abstract the target assembler from actual codegen in
most cases (we currently really do this in the IR only insofar as
"m_a" might be pointing at "m_astubs", but it's only safe sometimes).

This is just an RFC, because otoh there are less significant chunks of
direct assembler code in codegen.cpp, and maybe it doesn't matter much
unless we also switch "m_as" to be "a".  Thoughts?
2013-04-09 15:31:41 -07:00
jdelong 22005c4cfc DecRefKillThis needs the frame as an SSA dependency
We couldn't see this during ActRec elimination for inlining,
leading to bugs where the wrong this pointer would be decref'd and
then zero'd.  Also take the opportunity to remove a boolean parameter.
2013-04-09 15:31:41 -07:00
mwilliams 57a5cb6be7 Partition the tc into hot/cold sections
We already generate the data for this, so lets use it.
2013-04-09 15:31:40 -07:00
mikemag ab9e26f8af Avoid stack overflow on super-large expressions of binary operators.
A small change to optimize very simple binary operators in the parser. This avoids building very large parse trees for super-large expressions and folds binary operators involving two scalars directly in the parser. I've limited this to simple scalars since it's easy to prove they don't have anything too interesting going on in the other analysis phases leading up to BinaryOpExpression's normal folding. This works for all binary operators.
2013-04-09 15:31:40 -07:00
drussi bf740ca345 expose return type constraint (aka hint) from the AST to the runtime and reflection
This is the first part of the work to expose type constraint and generic all the way to reflection. This first DIFF exposes the return type with generic types coming next.
2013-04-09 15:31:40 -07:00
Owen Yamauchi 95afc7f255 Make NaN -> int casting explicit
See the task for details, but the bottom line is that casting NaN to an
int in PHP is passed straight through to the hardware's
convert-floating-point-to-scalar instruction. This implementation
explicitly spells out the Intel instruction's behavior. The ARM
instruction always outputs zero instead, resulting in inconsistency.

To be clear, I'm OK with not checking this in. For one thing, I'd bet
that if you compiled Zend on ARM, it would cast NaN to zero (I haven't
tried it). The advantage that this gets us is consistent output on all
platforms.
2013-04-09 15:31:40 -07:00
ptarjan 829a86d468 disable broken tests
@bsimmers says they are bad. I'll disable while I debug.

  mv test/zend/good/zend/bug31102* test/zend/bad/zend/
  mv test/zend/good/zend/ns_029* test/zend/bad/zend/
  mv test/zend/good/zend/ns_030* test/zend/bad/zend/
2013-04-09 15:31:40 -07:00
Owen Yamauchi 2755ecc9e5 Someone might want to run this test in another timezone 2013-04-09 15:31:40 -07:00
ptarjan 73663a2512 Allow script to be run without -z option
I switched to using a temporary directory for the test run, but never wrote a way to use the existing bad tests. Now it just copies the bad tests to ##all## and runs them there.

Should I rename this script? ##tools/zend_tests.py## or something?
2013-04-09 15:31:40 -07:00
jdelong c869cb47d8 ContEnter needs to depend on the frame pointer
ContEnter used rVmFp without making it visible in SSA.  This
didn't cause any issues yet because I've never tried to inline
functions that contain a ContEnter.
2013-04-09 13:01:47 -07:00
jdelong 6faa7cbea1 @override-unit-failures Initial support for <?hh typedefs and shapes
Adds runtime support for non-class typehints.  Typedefs are
introduced using type statements, and autoloaded via a new autoload
map entry.  Shapes are parsed but the structure is currently thrown
away and treated as arrays at runtime.  This extends the NamedEntity
structure to sometimes cache 'NameDefs', which are either Typedef*'s
or Class*'s.  VerifyParamType now has to check for typedefs if an
object fails a class check, or when checking non-Object types against
a non-primitive type name that isn't a class.
2013-04-09 13:01:46 -07:00
andrewparoski ebeecdb417 Add map(), filter(), zip() APIs for collections 2013-04-09 13:00:24 -07:00
ptarjan 4e16e58ef4 give up on matching Zend's error messges 2013-04-09 11:11:36 -07:00
ptarjan d8c3398698 Explicitly mark unsupported extensions 2013-04-09 11:07:59 -07:00
ptarjan 40583eaaa0 re-import everything with the new scanf implementation 2013-04-09 11:07:59 -07:00
ptarjan ecec3698d4 fix string funcs to return Variants
Convert another return type to Variant. I'm worried there are going to be lots of these. Thoughts?
2013-04-09 00:31:49 -07:00
bsimmers e55bfbe03c Better register allocation for DefLabel sources
Looking at some of the code generated by control flow was making me a
little sad, since it had avoidable register to register moves in hot
paths. This diff attempts to assign the same register to the destination of a
DefLabel and the corresponding sources of Jmp_s to that label. It works in the
small examples I've tried, but Perflab doesn't seem to care much (not
surprising since at best it'll eliminate some reg-reg moves).
2013-04-08 22:02:21 -07:00
jdelong c6770b6788 Disable HipHop syntax for verify_zend
A zend test defines a class called shape.
2013-04-08 22:02:20 -07:00
kma 8325c73d4e Stop constructing Strings for o_invoke.
Grepping around for string literals passed to o_invoke turned up these suspects. It's not a great practice. The only one that might matter to perf is the "count" invocation in ext_array.
2013-04-08 22:02:10 -07:00
andrewparoski d0321ec5aa Rename Tuple to Pair, restrict them to having exactly 2 elements 2013-04-08 21:41:07 -07:00
jdelong 7b243f97ed Remove enum abuse in recordSyncPoint 2013-04-08 21:17:46 -07:00
mwilliams ec35f444ee Get rid of contEnterHelper* (revert the revert)
It was identical to fcallHelper, except that if it couldn't get
a translation, it skipped over the prolog (and didnt call
the FunctionEntry hook, for example). That seems like a bug.

This removes it, cleans up funcBodyHelper to remove the special
cases for isGenerator, and modifies ContEnter to use
Func::prologTable()[1], rather than Func::funcBody() to dispatch.
2013-04-08 21:17:46 -07:00
mwilliams b9e7308acb Fix some bugs when we fail to get a translation
If we failed to get the translation for a cloned closure, we didnt
clean the registers.

VMRegAnchor::VMRegAncor(ActRec*,bool) didnt know how to set things
up for continuations, and had an unused bool parameter.

RetFromInterpretedFrame isnt suitable for returning from a
generator - so just preserve m_savedRip across the doFCall.
2013-04-08 21:17:46 -07:00
Owen Yamauchi 9c453b1ad0 Get rid of ext_hhvm_noinline.cpp, part 2
unserialize() and call_user_func_array() were straightforward. They were
called from all over the runtime, but I renamed those implementations
and codemodded the runtime.

The is_* functions were only ever being called by the CVarRef signature,
so I deleted all the other ones (same for f_gettype). Only some of the
is_* functions were being called from the runtime, so I made inline
versions of those without the f_ prefix.
2013-04-08 21:16:48 -07:00
kma 19e1eb22a3 Fix type buglet in RetC.
We can decRef an unguarded local from RetC now. This seems
like the right approach, so promote its type to Gen.
2013-04-08 14:05:20 -07:00
mwilliams dbf9403077 Revert "Get rid of contEnterHelper*"
This reverts commit 94d9bf9a5f
2013-04-08 14:05:20 -07:00
seanc b1e00e219b Add original filepath for continuations in backtrace 2013-04-04 15:39:04 -07:00
mwilliams 46e547b907 Use Func::m_funcBody to avoid SrcDB lookups 2013-04-04 15:39:04 -07:00
mwilliams 94d9bf9a5f Get rid of contEnterHelper*
It was identical to fcallHelper, except that if it couldn't get
a translation, it skipped over the prolog (and didnt call
the FunctionEntry hook, for example). That seems like a bug.

This removes it, cleans up funcBodyHelper to remove the special
cases for isGenerator, and modifies ContEnter to use
Func::prologTable()[1], rather than Func::funcBody() to dispatch.
2013-04-04 15:39:03 -07:00
kma b082ed0432 All inc and dec, all the time.
On older processors, inc and dec have some specific hazards associated with their preservation of the CF flag. Sandy Bridge doesn't suffer from this, so let's take the code size wins here. Thanks to Guilherme for updating my dated priors on this.

Also fix a pair of assembler bugs: no such thing as decl r32 on x64, and some decs were really incs.
2013-04-04 15:39:03 -07:00
mwilliams c4b56e312d Fix UnsetM with global base
If the global was not defined, it would try to return
a pointer into the MInstrCtx, which was not passed in.

We dont actually need it though, because in that case we can
just return a pointer to init_null_variant.
2013-04-04 15:39:03 -07:00
ptarjan 20ed47c5a1 kill dead code 2013-04-04 15:39:03 -07:00
ptarjan 0fbd3e35c7 add bcmath tests
All the bad tests seem to be error mis-matches. I already changed one error message about arguments so I think I should just make all these too many too few errors match.
2013-04-04 15:39:03 -07:00
ptarjan 2b85ccec0f switch to the same system as run-tests
My %s implementation needed backtracking, and instead of working on fixing that up, I switched to the same system as run-tests. This will serve way better as it is exactly their implementation.

Basically, instead of using the .diff I do the comparisson manually of .out and .exp using regexes. I'll go back through and re-import the other test diffs and see if things change. It worked well for the bcmatch tests (which is what I needed the backtracking %s for).

I used code from: https://github.com/php/php-src/blob/master/run-tests.php#L1895
2013-04-04 15:39:03 -07:00
ptarjan 339e0bfe26 don't import sapi tests
For things that we are intentionally not implementing, I don't think they should live in our repo at all. Do you agree? Or would you rather them all in the bad directory?
2013-04-04 15:39:03 -07:00
ptarjan 8e0f4cf43c import all tests from 'tests' and subdirs
I changed the import script to use a temporary directory instead of the bad directory. This makes is much faster to import only some files.

Done with:

  python tools/import_zend_test.py -z /tmp/php-5.4.11/ -o php-5.4.11/tests/
2013-04-04 15:39:03 -07:00
ptarjan e50740dd02 I found more tests...
So, I was being dumb and thought that that only tests zend had were in the folder called Zend/tests. On happenstance I typed a bad find command and found tons more tests all over the directory structure. I sort of figured out their directory structure and changed the importer to do all of it. Now we have an order of magnitude more tests. I didn't want a very deep directory structure so I replaced their ##/## with ##-##, but I'm open to other ideas.

The import script simulation of sscanf got crazyier since it now sees all sorts of nutty things like ##'%\0'##. I left the exception handing for errors incase zend adds more things that we need to parse.

Some of these tests are really really bad. They spew files all over your directory tree. Some with names that have nulls in them and other wonderful things. I'll start monkey-patching them. Only 1 test in the good directory does that, so I'll do that first.

Our coverage is MUCH worse now, but there are lot of unimplemented extensions and non .phpt file dependancies (@sgolemon not everything is encapsulated as tightly in one file). I'm sure I'll have some fun going through these.

We are at 2836 good and 9176 bad.

I've debated to use the actual php ##run_tests.php## but it seems very specialized. @sgolemon do you think it can't be wrangled into our tests? Or maybe output a compatible format?

I'm splitting the diffs up so we have a hope of hudson running them. I added the ##-o## option to help in that. This first diff basically moves all the tests into another dir but shouldn't change any. I'll send many other diffs for all the others tests.
2013-04-04 15:39:02 -07:00
mwilliams 016c4abe84 Fix issues with dead locals in backtraces
The specialized RetC sequence in tx64 destroyed each local,
and then set it to null in case onFunctionExit captured a
backtrace. But if the destructor of a sub-object captures
a backtrace, its already too late.

The same code in hhir didn't null out the local at all.
2013-04-04 15:39:00 -07:00
hermanv 1256f940ab Add the K flag to ConvObjToArr and ConvGenToArr.
Brett commented on another differential: CRc means the opcode takes ownership of a (probably recently created) reference to its source, either by decreffing it or by storing it into an object property, array, etc... It's true that these are generally used right after an incref, but the design of the opcode shouldn't assume anything about its use, especially for opcodes like this that can be generically useful.

Any opcode that decrefs one of its sources without guaranteeing that the refcount won't go to zero should kill that source. If you can guarantee that these instructions will never destruct their source then they don't have to kill the source.
2013-04-04 15:39:00 -07:00
ptarjan 78df5374d5 change func_num_args() from parser error to warning
I also introduced some code that I'll use to map their error messages to ours.
2013-04-04 15:39:00 -07:00
ptarjan 7cb07d22cf stop segfaulting in propery_exists 2013-04-04 15:38:59 -07:00
ptarjan 6e2868de3e allow recursive test running
I found a bajillion more tests in the Zend repo, and I'm going to have to namespace things. I think this solution will also be nice for the porting our C++ strings. One directory per package and then when you want to run them all you run the top-level.
2013-04-04 15:38:59 -07:00
ptarjan f7b2fac580 become consistent with zend for too few param error
I've been fighting with these in the importer. What do you think about being consistent? It gives an extra param of info too.
2013-04-04 15:38:49 -07:00
jdelong e72045d0e3 Remove some codegen traces 2013-04-04 12:20:04 -07:00
mwilliams 39ba801ffc More smart containers
And use them for VariableSerializer/VariableUnserializer
2013-04-04 12:20:04 -07:00
mwilliams 8dd81181b7 Fix cgJcc for bool comparisons with constants
The bool value is in the bottom byte of the register,
with the rest of the register undefined, but we were doing
a 32 bit compare.
2013-04-04 12:20:04 -07:00
kma 68ac3730f4 Do away with DumpIR.
DumpIR inconsistently interacted with the trace facility.
Move it to the hhir trace module. Compress a bunch of copy-pasta.
2013-04-02 15:01:37 -07:00
bsimmers 691b231fd1 Emit UnsetProp in VectorTranslator
I added this punt as a correctness fix while implementing
UnsetElem. It does show up as ~6% of remaining punts and it's easy to
do, so here it is.
2013-04-02 15:01:37 -07:00
bertrand d181040b4b Fix CreateCont for HHIR 2013-04-02 15:01:37 -07:00
jdelong c5db7e39ab Fix a bug with boxed static/counted types
When we box things, we need to forget whether we knew it was
static or not because we don't track when that might change.
2013-04-02 15:01:37 -07:00
jdelong eee109bdd5 SpillStack of an ActRec is a use of the old fp
A bug like this was bound to happen.  Thanks to whoever added
the assert for saving me from real debugging (@smith?).
2013-04-02 15:00:53 -07:00
ptarjan 2a9d6ec34d disallow Variant(TypedValue*) constructor
I was being dumb and hit this bug. Never again shall someone have this problem.
2013-04-02 15:00:53 -07:00
mwilliams 4e7457bd8c Fix FPushClsMethodD in hhir
Non-persistent classes can't be burnt in (or at least,
you have to check the target cache before using it).
2013-04-02 15:00:53 -07:00
jdelong eea87e32c6 Remove m_fpiStack
It doesn't appear possible to get a Func this way that we didn't
already have from static analysis.
2013-04-02 15:00:53 -07:00
ptarjan c04652f7aa fix test zend_import_test 2013-04-02 15:00:53 -07:00
mwilliams 1c329e4ba8 Add a test case for the scope of a closure generator 2013-04-02 15:00:53 -07:00
ptarjan f31278175a allow zend importer to run without zend directory
Most people won't have a full zend checkout, but I expect people to want to import zend tests. That's the whole point of having them checked in to the bad directory. Now you just do

  python tools/import_zend_test.py

and it will run all the bad tests and move the working ones to the good directory. The old way of doing it is now

  python tools/import_zend_test.py -z /tmp/php-5.4.11/

and if you don't want to re-run the binary (way faster) just do

  python tools/import_zend_test.py -n
2013-04-02 15:00:53 -07:00
hermanv 2a75bbce25 Introduce more helpers like Type::isArray.
class Type had methods isArray and isNull, but not methods like isBoolean. This change introduces helpers for the other types that frequently need to be tested for in type specialization code. The change is kept small so that is is obviously correct and easy to push quickly. Making all type tests consistent will have to be achieved incrementally.
2013-04-02 15:00:46 -07:00
jdelong 6ddd4be669 Fix an assertion in traceRet, relating to generator frames
This was firing in my sandbox.  I didn't find anything that
looked like it changed it recently, so I'm not sure why it wasn't
firing earlier.
2013-04-02 15:00:45 -07:00
mikemag e8c06b0312 Fix heredoc/nowdoc bugs with large docs, docs crossing buffer boundaries
Fixed a few issues in the lexer for heredocs and nowdocs. The source file is read in 64k chunks, and any time a doc was split across a buffer boundary the lexer would fail to consume the doc properly. Modified the lexer to refill the file buffer when it is used, or when more data is needed in a variety of cases. Also fixed a number of other corner cases where we'd fail to recognize the doc end label or other special characters. The old code was also a bit over- and under-flowy.
2013-04-02 15:00:45 -07:00
andrewparoski 31173142e1 Implement collection interfaces 2013-04-02 15:00:24 -07:00
andrewparoski f6ec5180bb Add addAll() and setAll() APIs 2013-04-01 14:26:59 -07:00
ptarjan 3b3963727d change exactly message
This fixes 005.php.

Shoudld we change our error message instead? We aren't even consistent with the error message for 001.php for func_get_args().
2013-04-01 13:48:59 -07:00
ptarjan 0defae9799 first monkeypatch of zend test
This test keeps making a file in my directory :(. How does this look for a monkeypatching setup?
2013-04-01 13:48:59 -07:00
ptarjan 5a094b72f2 Parse sscanf stuff from php tests
I originally just started copying their script which transforms %s to a regex, then run the regex. Then I realized their script does a ton more than they use in their test and was getting super compliected. This simple walking parser seems to do the trick. Escaping the regex for python's re was also being difficult.

This got us 145 more tests. yay.
2013-04-01 13:48:59 -07:00
andrewparoski 6e7b02933c Fix bugs with unserializing collections
The 'r' encoding for unserialization was broken for collections because the
code was calling Variant::unserialize() on a temporary Variant, which is a
no-no. unserialize() must be called directly on the value where it resides
in the collection.

Second, there was an inconsistency between serialize and unserialize with
how id numbers worked for the 'r' and 'R' encodings. This diff fixes
serialize and unserialize to count collection keys when assigning id
numbers. I also took the opportunity to tighten up enforcement to prevent
collections keys and values from being taken by reference when during
unserialization.
2013-04-01 13:48:59 -07:00
mwilliams 17f2ae8df7 Fix the context class for continuations in closures
The late static bound class was being used for the context. This
was wrong, but before this change there was no context at all, so
it would have taken newly written code to expose the bug.

However, a given continuation can be instantiated from a large number
of different lsb classes (but only one context class) which meant that
we got an explosion of unnecessary translations.
2013-04-01 13:48:50 -07:00
mwilliams bfd325be43 Prevent a race in RecordFunctionInfo
We were calling RecordFunctionInfo on every builtin function/method
every time we parsed a file (in non-repo-auth mode). Once this has
been done once, its just a no-op. But if multiple threads try at the
same time, we can get a race inserting into an unlocked hash table.

Move the calls into ParseExtFunction which avoids the race (we
guarantee to call BuiltinFunctions::Load from a single thread at
startup time), and avoids doing redundant work for each file parsed.
2013-04-01 13:48:50 -07:00
bsimmers b7d72e3894 Fix baseValChanged check for empty base promotion in VectorEffects
I thought I'd have to teach memelim about the PtrToBoxed*
srcs for vector instructions but it turns out the refactoring I did in
the UnsetElem diff was enough. It already clears out the local map for
instructions that may modify refs.
2013-04-01 13:48:50 -07:00
mwilliams 5b0c146e4a Fix a crash in exif processing
Given a zero length string, the pointer was left unset, but
later code checked if the value of the pointer was non-null,
and ignored the length.
2013-04-01 13:48:50 -07:00
ptarjan 329d6c3aa3 Handle "line %d" and extra lines for errors in expected output 2013-04-01 13:48:50 -07:00
jdelong 40f61f6686 Remove ... when hphpc prints the hhvm command line 2013-04-01 13:48:50 -07:00
ptarjan be704f1faf import zend tests
This is a first pass looking for suggestions.

    348 / 1268 passed (27.44%)

I modified the script, then ran:

    ./tools/import_zend_test.py /tmp/php-5.4.11/

which created all the zend tests. When they send out a new update, this script is idempotent so running it on the new tests should just make the working directory in a good enough state to commit.
2013-04-01 13:48:31 -07:00
mwilliams ec4e62d602 Fix closure dispatch when there's more than one Func*
We need to make sure that we execute the code
corresponding to the actual Func*. This re-uses the
prolog array to hold the entry points for the cloned
Func*.
2013-04-01 13:47:50 -07:00
bsimmers b8ebb48421 Profile vector instruction shapes
This adds a new profiling mode for vector instruction
shapes. I'm planning on using this to identify any common cases that
may be worth special casing, like we do for simple SetM, CGetM, and
IssetM instructions. Instead of adding Yet Another Hashtable Stats
Map, I created a generic version and changed TRACE=punt:1 to use it as
well.

I also changed emitInterpOneOrPunt to use a more specific name.
2013-04-01 13:47:50 -07:00
bsimmers 66a84f861d Implement VectorTranslator::UnsetElem
Fairly straightforward. The only interesting part is the
addition of ElemUX, which behaves similarly to ElemDX in terms of
side-effects (but not exactly the same).
2013-04-01 13:47:50 -07:00
seanc c6d10ce255 Add HPHP support for newInstanceWithoutConstructor
Add support for PHP >=5.4 ReflectionClass::newInstanceWithoutConstructor
2013-04-01 13:46:30 -07:00
bsimmers 7d7edb8be2 Implement all of VerifyParamType in hhir
TranslatorX64 interps cases that it expects to fail but I
didn't like that, so the hhir version never punts or interps. The fast
path code reuses the stuff Jordan added for InstanceOfD and should be
the same as tx64's, modulo some branch fusing that doesn't appear to
matter in perflab.
2013-04-01 13:46:30 -07:00
bsimmers 88f1bcf907 Strengthen filepath.filter and make it run for all tests
It now handles filenames in strings that have been
var_dumped, without having to special case them. I also renamed it to
default.filter and changed verify to run it on every test. This lets us
remove a lot of symlinks that used to point to filepath.filter and
changed the expected output for a bunch of tests.
2013-04-01 13:46:30 -07:00
seanc 4a6ae52f5d Generators should show original name in backtrace
Use the original name instead of the outer name for generator
functions in backtraces
2013-04-01 13:46:30 -07:00
ptarjan a2c5921413 fix double space after notice and warnings
We are inconsistent with how many spaces happen after ##:## Errors have one, but warnings and notices have 2. I went with 1 because that is what Zend does.
2013-04-01 13:46:30 -07:00
Owen Yamauchi 0fd0fa814c Get rid of ext_hhvm_noinline.cpp, part 1
Post-hphpc, declaring builtins as inline is useless, which obviates the
need for this layer.

This doesn't fully delete the file, because I wanted to keep mindless
parts and use-your-brain parts separate. This is the mindless part. The
remaining functions in noinline.cpp are no-inline wrappers around
(a) a function that isn't defined in an extension, call_user_func_array,
and (b) calling polymorphic is_* functions, which can probably mostly go
away now. But I wanted to exercise more care around those, so they'll
come in a followup diff.
2013-04-01 13:41:49 -07:00
mwilliams ed6ac5d10f Fix refcounting issues with string SetM
The code was assuming that the result of the assignment
would be the value assigned, but its actually a new string
containing the first character of the value assigned. The result
was that the SetM had already decRef'd the rhs, and then the
jitted code decRef'd it again. Since that last decRef was a decRefNZ,
we would often get away with simply leaking both the original rhs and
the value of the SetM. But the new testcase crashes in a DEBUG build
without the fix.
2013-04-01 11:51:38 -07:00
smith 22058efe41 Allow different RefData and TypedValue layouts
Fixing various bugs all over the VM that make assumptions about RefData
and TypedValue layout.  Here are the assumptions fixed by this diff:

offsetof(RefData, m_tv) == 0.  Both JIT's assumed this in many subtle
ways, by punning RefData* as TypedValue* without adding an offset.
This assumption also causes RefData._count to overlap TypedValue.m_aux,
which constraints TypedValue layout.

offsetof(TypedValue, m_data) == 0.  gen_ext_hhvm.php assumes you
can cast TypedValue* to Value*; the JITs often weren't using
offsetof(TypedValue, m_data) in their addressing calculations.  HHIR
assumed return-by-value TV's have m_data/m_type in rax/rdx, which
can change when TV layout changes.

offsetof(TypedValue, m_type) > 8 is an assumption baked into the
pass-by-value register assignment logic in HHIR's codegen.cpp; if
the type is in the low word, register assignment is swapped.

sizeof(TypedValue::m_type) == 4.  We used dword-sized operations
in both JIT's when accessing m_type.  Now, we use helper functions
that are sensitive to sizeof(DataType)

Configuration:
DEBUG=: (opt)  same layouts as trunk for RefData & TypedValue
DEBUG=1: (dbg) new RefData layout (m_tv doesn't overlap RefData::_count)
PACKED_TV=1, DEBUG=*:  new RefData and TypedValue layout.
2013-04-01 11:51:31 -07:00
smith 55c20f79c1 Tighten tvIsPlausible() checks
I've found several bugs recently due to the TypedValue plausible
check being too loose.  Our DataType enum values are now sparse,
and we miss garbage that happens to fall inside the [-10, 127]
range, which is >50% of possible garbage values.
2013-04-01 11:51:31 -07:00
andrewparoski 5b8111f402 Chip away at ClassInfo::FindClass() and ObjectData cruft 2013-04-01 11:51:31 -07:00
mwilliams 0ddaed959d Fix assert in CodeGenerator::emitTypeCheck
The vector translator produced a type that was
boxed-array-or-string, which we couldnt guard on.

Since applying a SetM to a string will almost always produce
a string, change it to report string instead (which will still
be guarded on).
2013-04-01 11:51:30 -07:00
mwilliams 4976bf8379 __lvalProxy needs to be request local
But it was recently made thread local. If the value left
in it at the end of one request was smart allocated, the
next request would try to free it - but after its already
been swept.

We could make this RequestLocal, but that seems to add even
more overhead. We could probably make it a __thread TypedValue,
and just set it to uninit at the start of each request (and then
tvAsVariant() where its used). This just puts it back to how
it was, since global_variables() is already being dealt with
appropriately.
2013-04-01 11:51:30 -07:00
smith 13394d0525 Remove dead lvalPtr(int-key) API 2013-04-01 11:51:30 -07:00
Sara Golemon f436534766 Add install target (and remove errant install targets from 3rd party)
make install
  Installs hhvm and systemlib.php to CMAKE_INSTALL_PREFIX/bin

To override the default location define it during cmake:
  cmake -DCMAKE_INSTALL_PREFIX=/usr/hphp .
2013-03-28 23:53:20 -07:00
Sara Golemon 316f2b13db Update folly 2013-03-28 23:09:16 -07:00
Sara Golemon ba168876d3 Remove unused files and set master branch to declare HPHP_VERSION==2.1.0-dev 2013-03-28 16:07:30 -07:00
mwilliams f03fb8ca06 Fix TestServer/TestXboxServer
A recent change to xbox makes it reset after every request.
This broke a test which was testing that threads only get
reset when they ask to be reset.
2013-03-28 12:28:17 -07:00
jan 1da3705450 Cleanup Static{Result,Exception}WaitHandle construction interfaces
Provide a Static{Result,Exception}WaitHandle::Create() static method for
internal use, use it by GenArrayWaitHandle.

Avoids one inc/decref (Array -> Variant -> m_resultOrException) if
GenArray received an array of finished dependencies.
2013-03-28 12:28:17 -07:00
Sara Golemon 1a579441fb Switch to reentrant safe calls in posix
posix_getpwuid()
posix_getpwnam()
posix_getgrgid()
posix_getgrnam()
posix_ttyname()

were using non-threadsafe posix calls.
Most using AttachLiteral for shared space as well.
2013-03-28 12:27:01 -07:00
jdelong 7baa9acbaa Move some cold stubs from a to astubs
Bertrand's profiling data showed we're wasting the first 3
cache lines of a.  Move defClsHelper and the (now rarely used)
non-generic decref stubs to astubs.  Also adds some tracing I was
using to see how big and where things are.
2013-03-28 12:03:11 -07:00
jan 3adce96fdc Remove markCurrentAs{Succeeded,TailCall}
Tail calls were eliminated, results are set thru ContRetC opcode, these
functions are no longer needed.
2013-03-28 12:02:53 -07:00
jan 20b8aeea2f Consolidate ContDone into ContRetC
Merge ContDone+ContExit into ContRetC with added support of passing results. This variable passing mechanism is not exposed to the PHP as the ReturnStatements in generators do not contain result expression. However, this is exposed by restored hphp_continuation_done() built-in to allow experimentation.

The idea is that once we introduce ContYield opcode (merge of all opcodes used by YieldExpression), we could change ContRetC and ContYield to leave result and done-status on the stack and leave it up to the caller (ContNext/ContSend/ContRaise) to fill in Continuation fields. This will make these opcodes more generic and useful for other things, while allowing us to move some properties to the VM and kill opcodes like ContCurrent.
2013-03-28 11:05:47 -07:00
hermanv cd6fa358d5 Split up ConvToDbl into sub-opcodes.
Split up ConvToDbl into ConvArrToDbl, ConvBoolToDbl, ConvIntToDbl,
ConvObjToDbl, ConvStrToDbl and ConvGenToDbl, so that different flags
can be set for each instruction.
2013-03-28 11:05:43 -07:00
jan 6822bc55cc Early release of m_received value
Continuation::send() uses m_received field to transfer the value inside
the continuation. This field remains set until the continuation is
iterated the next time.

Unset this field early by ContReceive so that the memory can be
reclaimed.
2013-03-28 11:05:42 -07:00
bsimmers a15b680acc Remove special cases for vector instructions in the ir
VectorTranslator is now good enough that all of this code can be
removed without causing a perf regression. Instructions, loads, and stores are
all slightly up, but CPU time looks like noise.
2013-03-28 11:05:42 -07:00
bsimmers 3ec24e45d6 Fastpath for simple array IssetM
TranslatorX64 has a fast path for this case so I thought I'd
try it out in the ir. It's a small but apparently real win in Perflab.
2013-03-28 11:05:42 -07:00
ptarjan 3710ac0713 Remove duplicately named variables from a closure class
Remove it from the usevar list. Also, add assert to catch stack pointer bugs.
2013-03-28 11:05:42 -07:00
Sara Golemon b8868a1c40 Cast result of unpack to uint64_t when requesting unsigned type 'I'
ZendPack::unpack() always returns a signed int32_t,
regardless of actual storage type being unpacked.  For 32bit
unsigned types ('L', 'N', 'V', and 'I'(on I32 systems)) this
means overflowing in the helper and we have to explicitly
recast it to a uint64_t to get the data back out.

For LNV, this was already handled, it was missed for I.
2013-03-27 17:39:44 -07:00
Sara Golemon 463ce4edd5 Remove dead extprofile generators
While looking into another matter I noticed this dead code lying around.
It has no callsites because we don't have extprofile files anymore.
2013-03-27 17:39:44 -07:00
kma 5e603184f5 De-virtualize ArrayData::release.
Of the four horsemen of the SmartAllocator, ArrayData was the only virtual
call. This meant an extra layer of indirection when coming from the TC
to allow the c++ compiler to emit its virtual call, and slightly larger
callsites when using non-generic paths.

While we're moving in this direction, consolidate ArrayData introspection
on its type enum. isSharedMap() was previously implemented with a vtable
slot, and we had no way of asking if an ArrayData was a NameValueTable.
2013-03-27 17:39:41 -07:00
ottoni 56cfa9c73c Eliminate IncRef/DecRef pair when a method returns $this
Instead of generating IR like:

   t1:Obj = LdThis t0:StkPtr
   t2:Obj = IncRef t1:Obj
   ...
   DecRef t1:Obj
   RetVal t2:Obj
   ...

This diff changes HhbcTranslator to produce:

   t1:Obj = LdThis t0:StkPtr
   t2:Obj = IncRef t1:Obj
   ...
   DecRefNZ t2:Obj
   RetVal t1:Obj
   ...

This enables the ref-counting optimization to kick in.
2013-03-27 17:39:41 -07:00
jan c2469a8f85 GenArrayWaitHandle: import all children on enterContext
If a GenArrayWaitHandle is imported, the current implementation imports
only the active child. Try to import other children as well to increase
parallelism.

enterContext() can throw an exception if a cross-context dependency
cycle is found. It is safe to ignore such exception when importing
non-active children. The import will be attempted and fail again once
onBlocked() reaches the dependency that causes the cycle.
2013-03-27 17:39:41 -07:00
jdelong 2c72411dae Don't use LdClsPropAddrCached for properties that might not be accessible
Tx64 only translates CGetS when you do it with the context
class the same as the class being looked up, to avoid the need for
accessibility checks.  The IR can translate it more often, but was
using its fast path even when it was not safe to do so: if a previous
(safe) access had allocated a targetcache entry, later accesses would
be able to get to the property without an access check.  For now just
limit the optimiation to safe cases.
2013-03-27 17:39:41 -07:00
jan 4a2dc584f8 GenArrayWaitHandle: verify input array in advance
Verify sanity of input array of dependencies in advance. Callers get the
error earlier and it also makes it easier to work with the array outside
of the main loop.
2013-03-27 17:39:19 -07:00
mwilliams 46fe09ca5e IncDec bool needs to push a value
In the ir, it didnt, resulting in crashes/bogus values
2013-03-27 17:39:18 -07:00
andrewparoski ee2d13b031 Add add() API for collections 2013-03-27 17:38:50 -07:00
smith d55c44a8ca Fix some RefData<->TypedValue<->Variant<->Value type puns
Our ext_hhvm generated code is casting TypedValue* to Value*
on the assumption that the offset of TypedValue::m_data is 0.
Fix this assumption, and also while in the same code, replace
some (t == KindOfString || t == KindOfStaticString) with
IS_STATIC_STRING(t), which does a single bit test instead of
two comparisons.
2013-03-27 16:52:16 -07:00
bsimmers b4ed082dd7 Add a fastpath for simple array CGetMs to VectorTranslator
This is modeled after TranslatorX64's emitArrayElem.
2013-03-27 16:10:46 -07:00
Alex Suhan fb121815dc Merge {get, set}HelperPre 2013-03-27 16:10:46 -07:00
kma aa3487dc78 Get rid of some destructor wrappers.
Many destructors were going through a C++ trampoline that did
nothing but turn a C call into a method call. Get rid of these where
possible. ArrayData still uses a virtual release, which is unfortunate
but cannot be helped at the moment.
2013-03-27 16:10:46 -07:00
steveo b4ca4bbbd0 change use of html_supported_charset to avoid duplicating work
change callers of determine_charset to check for nulls, instead of calling html_supported_charset (to pre-validate charset name) and then calling this (which has to run through a list of names anyway).
2013-03-27 16:10:33 -07:00
andrewparoski d61c30ded8 Add containsKey() API 2013-03-27 15:56:06 -07:00
andrewparoski bb2df58a2f Add items(), keys(), and fromItems() APIs for collections 2013-03-27 15:30:16 -07:00
Sara Golemon 0690c787e4 Prevent non PHP licensed files from being overwritten 2013-03-27 13:06:09 -07:00
aalexandre 42ec075946 ArrayData.* improvements
A few simple refactorings and optimizations for array_data. Perflab results (CPU time %) are on the desired side of noise: 22/23 show reduced times, 12/23 green, no red, best -2.2%, worst +0.3%.
2013-03-27 11:40:17 -07:00
jan a131e5232e Handle invalid Continuation state at start time
In an unlikely situation a user of ext_asio may tamper with Continuation
before passing it to the ext_asio extension. Let's fail with an
exception if this happens. Previously, a user bug would stay unnoticed,
but would not harm the ext_asio code.

This check will be needed once we implement optimistic execution. With
optimistic execution, we iterate continuation and defer construction of
ContinuationWaitHandle until the first blocking event occurs. During
this phase, a standard dependency loop detection is skipped and the code
would try to iterate a continuation that is already being iterated.
2013-03-27 11:40:17 -07:00
bsimmers afc455cf07 Put VectorTranslator helpers in a namespace
By making them not static they'll show up in TRACE=stats
output and when printing IR.
2013-03-27 11:40:17 -07:00
Sara Golemon 3a6c4e2626 Minor cleanup to hphp/CMakeLists.txt
ext/sep no longer exists
Make test exclusions generic
2013-03-26 12:06:47 -07:00
bsimmers 1467bee4a5 Add null base support to VectorTranslator
The only changes necessary were splitting PropX into PropX
and PropDX/PropDXStk and loosening the type check in
VectorTranslator::getInput.
2013-03-25 13:31:17 -07:00
mwilliams 73f6c7f9c4 Add option to not delete perf-pid.map on exit
Its useful to keep it around for command line scripts
2013-03-25 13:31:17 -07:00
smith e82aaf0281 Removed unused helperFromKey() function in translator-x64-vector.cpp 2013-03-25 13:31:17 -07:00
ptarjan 6e8eb46729 convert init_closure into assembly
I got to do a few optimizations:

* burn in the number of use vars
* not write out uninitialized use vars
* use the staticness of the method as a hint for the incRef
2013-03-25 13:31:17 -07:00
ptarjan bb40c64e25 fix this callsite incase someone ever does the TODO for setting valueClass() 2013-03-25 13:31:17 -07:00
ottoni afe1b1a705 Don't spill to mmx.
There is not a clear path forward to safely using MMX registers as
scratch storage. Doing so spoils the state of the legacy x87 FPU, and the
x64 ABI uses the x87 FPU to implement long double. Our options are to
either:

  1. Prohibit use of long double in source code (or x87 instructions in
     machine code). Given that we have a dynamically linked binary that
     includes system libraries outside our control, open source that needs
     to be patched, fbcode, etc., this could prove difficult.

  2. Always execute an FPU resetting instruction before transitioning from
     TC code to C++. For all I know, these instructions are cheap, but it
     still seems like an unfortunate overhead to impose everywhere; since
     we don't want to mark every helper with a "reset fpu" call, we'd
     probably end up bloating callsites.

  3. Admit this doesn't work.

In the absence of evidence this matters for perf, I lean towards 3.
2013-03-25 13:31:17 -07:00
mwilliams 4c6cb0a577 Fix getContextClassName and getParentContextClassName
They both returned the late static bound class, not the context
class. This meant that eg "constant('self::FOO')" was actually
returning what "constant('static::FOO')" should have done.

In addition, we often want the Class*, not its name, so
change them to return Class*. The remaining places that then
read the name from the Class* should be fixed to use the Class*
directly (in a later diff).

Finally, noticed that while "defined()" was recently fixed to
support "static::", "constant()" was not. Pulled out a common
function to find the correct Class*.
2013-03-25 13:31:17 -07:00
mwilliams b387d70e70 RetC needs to zero ActRec::m_this before destroying it
In the case where m_this was already in a register,
and known to be non-zero, we would fail to zero the ActRec's
m_this field, which could result in a dangling reference
to $this being captured by debug_backtrace.

Put the store on the presumably cold path. Fix DecRefThis to
do the same.
2013-03-25 13:31:16 -07:00
smith 768a8bd238 Fix type-puns in FCallBuiltin
Avoid punning TypedValue* to String&/Array&/Object& in FCallBuiltin
(all three implementations).  Our native function calling conventions
require passing pointers into a TypedValue for these types, and
pointers-to-scratch for return values.

In the HHIR case, I removed the optional "return pointer" argument
from the IR CallBuiltin instruction.  The C++ value-passing ABI details
are now handled in cgCallBuiltin and are no longer exposed in the IR.
The argument types are still PtrTo*, but we handle the address fixups
in CodeGenerator.
2013-03-25 13:31:16 -07:00
ptarjan a5b7b243d6 add test
Never shall this happen again
2013-03-25 13:31:16 -07:00
ottoni 659da8c6b1 Fix assertion in ref-count optimization
MemElim may transform the source of a DecRefNZ into a constant,
so we shouldn't assert that it's coming from an IncRef.
2013-03-25 13:31:16 -07:00
Alex Suhan b41346c929 Fix ext_asio callback checks
The callback passed to asio_set_on_{failed, started}_callback was
never null because the way types for input parameters work in
extensions. Null from user PHP code was converted to a stdClass
object, triggering an exception.
2013-03-25 13:31:09 -07:00
hermanv e778550bef Break up IR ConvToArr into sub opcodes.
ConvToArr has at least two variants: one that holds on to the object being converted and the other that does not. Having separate opcodes allow this distinction to be made. Making separate opcodes for each type of operand makes for a more consistent IR.
2013-03-25 12:44:12 -07:00
ptarjan 6b61441bd9 more isStatic fixed for closures
The interpreter fix was different than the jit/ir fix because ##translateFPushObjMethodD()##'s ##i.inputs[0]->rtt.valueClass()## is null (with a TODO in the code to make it not null). It then goes into the slowpath.

Another one like this and I think I should have a different attribute for static closures :(
2013-03-25 12:44:12 -07:00
jan 10b770d342 Simplify hphp_unpack_continuation
Do not generate yield labels as normal goto labels in the parser. Create
them at YieldExpression and use m_yieldLabels array in emitter.
2013-03-25 12:43:42 -07:00
jan 06713e6226 Eliminate transform_yield_break()
The only places where ReturnStatement is constructed are:

- onReturn(check_yield=true) -> not allowed in generator
- onReturn(check_yield=false) -> coming from transform_yield_break, right after creating hphp_continuation_done()
- MethodStatement, end of function call -> hphp_continuation_done() is created at end of generator in prepare_generator()

Emitter is emitting ContExit in ReturnStatements used in generators. As
can be seen from the analysis above, it's always preceded by emitting
ContDone from hphp_continuation_done(). Let's emit ContDone inside the
ReturnStatement directly and kill usage of hphp_continuation_done().

transform_yield_break() becomes a simple onReturn(check_yield=false), so
let's inline it into onYield and create ReturnStatement directly. After
this change, check_yield flag is always true and can be killed.

ContExit was also used after emitting a generator method in case the end
of method is still reachable. ContDone is added so that the generator is
properly closed. I believe this is never actually used, as MethodStatement
creates ReturnStatement at the end of method anyway.
2013-03-25 11:31:17 -07:00
ptarjan 5ce11ce940 get static locals from the first local AFTER the params
I directly copied continuations for this, but they never have params. Closures sometimes have params, and the closure itself will be the first local AFTER those.
2013-03-25 09:49:51 -07:00
alia c3130d24f6 Added DecRefNZOrBranch and basic memory tracking to enable additional IncRef-DecRef elimation for Set[S,G,M].
Added a new IRInstruction, DecRefNZOrBranch, that decrefs but
branches out of the trace if the reference count is about to go to
zero. This guarantees that no destructor will run, and thus no memory
side effects on trace. Tracked the last value available in memory in
TraceBuilder and used it to convert DecRef instructions to
DecRefNZ. These 2 changes allow us to eliminate more IncRef-DecRef
pairs, in particular cases due to SetS, SetG & SetM; for example:

85: SetS
    (20) t12:Cls = LdStack<Cls> t10:StkPtr, 1
    (21) t13:Str = LdStack<Str> t10:StkPtr, 2
    (23) t15:PtrToGen = LdClsPropAddr t12:Cls, t13:Str, Cls(0)
    (24) DecRef t13:Str
    (25) t16:PtrToCell = UnboxPtr t15:PtrToGen
    (26) t17:Cell = LdMem<Cell> t16:PtrToCell, 0
    (27) t18:Obj = IncRef t11:Obj
    (28) StMem [t16:PtrToCell]:Obj, t11:Obj
    (36) DecRefNZOrBranch t17:Cell -> L4
  L5:
    (38) DefLabel
  86: PopC
    (39) DecRefNZ t18:Obj

In the above example, memory tracking and DecRefNZOrBranch allowed us
to change instruction (39) from a DecRef to a DecRefNZ. Subsequent
dead-code elimination will remove the IncRef instruction (27) and
DecRefNZ instruction (39).

This diff does not handle SetM.
2013-03-25 09:49:51 -07:00
jan 7b7343b56a Introduce YieldExpression
Unhack the parser and introduce YieldExpression that emits the
equivalent set of opcodes that were emitted by bunch of
expressions/statements generated by parser before.

YieldExpression expects evaluation stack to contain just the value
being yielded, so {,List}AssignmentExpression need to evaluate RHS
first. The previous code had the same behavior.

This will let us consolidate continuation-related opcodes and make
them less tied with continuation objects.
2013-03-22 13:01:05 -07:00
jan 8fa1c51ee8 Fix ref generator parameters
Alias manager does not know whether generator parameters are passed by
reference. This didn't matter, because every generator had at least one
function call (hphp_continuation_done()) that pretty much disabled unused
variable elimination.

This diff fixes that, lets us get rid of artificial function calls in
generators and will allow later improvements in alias manager.
2013-03-22 11:48:50 -07:00
mwilliams 8ad18a7be9 Filter strict_warnings like notices
There is a runtime option to filter out notices and warnings,
but strict_warnings were left out. Bundle them with notices.

We raise a lot of strict_warnings; and when we fix hphpiCompat
(to match zend better) we will raise a lot more, so this could
matter.
2013-03-22 11:48:50 -07:00
bsimmers 7219dec255 Implement more final operations in VectorTranslator
Most of this is pretty boring and mechanical. I added
VectorProp and VectorElem flags to help deal with the increasing
number of vector-related opcodes.
2013-03-22 11:48:50 -07:00
ottoni 5e6a53319f Disable spilling into MMX registers 2013-03-22 11:48:50 -07:00
Drew Paroski e421b15e38 Update README.md 2013-03-21 22:01:03 -07:00
Drew Paroski fb520b5351 Update README.md 2013-03-21 21:59:48 -07:00
Drew Paroski ee8aa92547 Update README.md 2013-03-21 21:58:41 -07:00
Drew Paroski eabe841fcd Update README.md 2013-03-21 21:53:37 -07:00
Drew Paroski 90a5b30639 Update README.md 2013-03-21 21:51:58 -07:00
Drew Paroski 450a0fb2f5 Update README.md 2013-03-21 20:48:14 -07:00
Drew Paroski 1dbb3c6423 Update README.md 2013-03-21 20:47:22 -07:00
Drew Paroski 6e030ca9d1 Update README.md 2013-03-21 20:44:37 -07:00
Drew Paroski 07504c37e8 Remove outdated info 2013-03-21 20:43:28 -07:00
jan f9765d1c58 Fix local propagation of generator parameters
Alias manager does not know that generator parameters are populated and
assumes they are uninit. The current code works because control flow
algorithm gives up while trying to deal with the continuation switch
statement full of gotos.

This diff fixes it by setting isGeneratorParameter flag in symbols
representing parameters of enclosing generator wrapper and use variables
of enclosing closure.
2013-03-21 19:33:53 -07:00
aravind 7a58a78ef1 Don't handle signals in non-HPHP threads
This is not correct, as we are dropping signals because
they got sent to non-HPHP threads.
2013-03-21 19:33:53 -07:00
jan fcb32cf8ac Kill needs{ObjTemp,RefTemp,CheckMem} and cppTemp 2013-03-21 19:33:53 -07:00
kma 4fcf2ec200 Get rid of a dead load from some tx64 unboxes.
Slight change to assign operations that affect the inner type.
This gets rid of an unnecessary load in some cases. I have little evidence
that this is practically important, but when debugging on 7pack I found the
dead load confusing.
2013-03-21 19:33:53 -07:00
hermanv c23fe753c5 Fix refcounting problems in convToArr.
This set of changes fixes problems pointed out in earlier diffs by Ed and Brett, mostly centered on redundant ref counting. It will be followed up by another diff that does a mechanical refactor to introduce variants of convToArr, specialized on the types of it operand.
2013-03-21 19:33:53 -07:00
philikon d79cb16bfe Implement UConverter::getStandardName()
Making ucnv_getStandardName() available as
UConverter::getStandardName().
2013-03-21 19:23:54 -07:00
mwilliams 737a8c87b1 Cleanup more unused code in Continuation
m_method was unused, and __construct had a couple of
unused parameters. Also bring the idl back into sync.
2013-03-21 17:52:28 -07:00
Owen Yamauchi b5a11c6139 Fix the RIP_REGISTER macro
Pretty simple. This makes me slightly nervous because I've only
confirmed it works in my stupid OpenEmbedded ARM SDK; a different Linux
might call this something else. But we'll cross that bridge when we get
to it, and this works for now.

I'm also sneaking in a change to remove x29 from the list of
callee-saved regs; I put it in there by accident last time.
2013-03-21 17:31:37 -07:00
jan 06aefe7e37 Remove deprecated support for priority in ContinuationWaitHandle::start()
PHP code does not use this anymore. Let's remove the support.
2013-03-21 17:31:09 -07:00
jan 6d3f04d0a9 Remove deprecated yield array(...), try #2
Our PHP code no longer yields arrays. Remove.
2013-03-21 16:51:06 -07:00
ptarjan a6d70040fa fix static closures
I added the check for this in the interpreter but ##f_array_map## re-enteres the VM via a different path than FCall. Here is the equivilent check for the VM.
2013-03-21 16:51:06 -07:00
mwilliams 9c78f77577 Fix args for embedded repo
When we generate a binary with an embedded repo,
we add various args (-vRepo.Authoritative etc) to the end
of the command line. But the argument "--" is taken to mean
"pass the rest of the args to the script". So if you use
"--" on such a binary, it gets rather badly broken.

Reorder the args so that the inserted ones come first.
2013-03-21 16:50:55 -07:00
mwilliams 97eb859975 Remove unused nextImpl template from c_Continuation 2013-03-21 16:50:55 -07:00
ptarjan a1802db1d2 allow static keyword before closure
PHP added this in 5.4 so that you can say your closure shouldn't capture ##$this##. https://wiki.php.net/rfc/closures

Should we add it? Many of their unit tests use it.

Instead of putting a boolean somewhere I used the same attr framework and set the static bit there. Thoughts? It only needs one change in the ##FPushFunc##.
2013-03-21 16:50:55 -07:00
ptarjan 4d7004e955 :Allow $this on closures
In Zend 5.3 they decided that closures should inherit the ##$this## from the containing scope. This brings us close to paraity with them. The remaining thing is to make

    function() use ($this) {}

fatal after we purge it from WWW.
2013-03-21 16:50:12 -07:00
hermanv 3718c612ed Split Conv<T> into type specialized ConvToArr, ConvToBool, ConvToDbl, ConvToInt, ConvToObj and ConvToStr instructions.
This is a "mechanical" refactoring that is not supposed to introduce any new behavior or to fix anything. It sets the stage for further changes that will reduce the number of places where code generation punts.
2013-03-21 16:13:35 -07:00
jdelong dd71b738dd Fix ODR violation in TestExtCurl
TestExtCurl was failing in the fbmake build, because for some
reason the other TestServer was being used.  AFAICT it's within the
compiler's rights to do whatever it wants here, though.
2013-03-21 16:13:21 -07:00
hermanv 186882bae7 Add more unit tests for conversion operations.
A batch of small sanity tests for the new conv instructions.
2013-03-21 16:13:21 -07:00
chip f258edcbc5 Re-enable millisecond mysql timeouts 2013-03-21 16:13:21 -07:00
mwilliams 1d68430f6a Always setup Repo paths in hphp mode
We didnt do it for the analyze target, for example,
which resulted in hphp hanging on some machines due to
trying to create ~/.hhvm.hhbc
2013-03-21 16:13:21 -07:00
bsimmers 62710cb083 Disable flaky TestExtPdo-test_pdo_mysql 2013-03-21 16:13:20 -07:00
ptarjan cc37fe637a add Callable typehint
php-5.4 has it http://www.php.net/manual/en/language.types.callable.php
2013-03-21 16:13:20 -07:00
ottoni 041d737d3f Avoid storing to the stack the same value just loaded from there
Sometimes SpillStack and Call end up storing onto the stack a value
that was just loaded from the same stack location.  There was already
code in cgSpillStack to avoid the extra stores in some cases, but that
still kept the LdStack alive.  This diff detects some of those cases
with SpillStack in the Simplifier, which allows the LdStack to be
eliminated by DCE.  This diff also adds similar support for Call.  The
operands that don't need to be store onto the stack are replaced with
None.

Note that the optimization in cgSpillStack is not subsumed by this
diff.  In the Simplifier, we cannot chase through IncRefs as done in
cgSpillStack -- that would result in an IncRef that is not consumed.
2013-03-21 16:13:20 -07:00
jdelong d44f93f14e Remove unused buildTarget function in compiler.cpp 2013-03-21 16:13:06 -07:00
jan c2b38ad2b1 {,List}AssignmentExpression: add support for RHS first evaluation order
Add a flag to {,List}AssignmentExpression that changes evaluation order
to RHS before LHS.

This will be used by YieldExpression.
2013-03-21 16:13:06 -07:00
Alex Suhan 1742a79189 Add on started callback to AsioSession
The PHP code using Awaitable interface will need this.
2013-03-21 15:55:58 -07:00
jdelong 6f82cce043 Update Setprofile test 2013-03-21 15:17:33 -07:00
mwilliams cbf041b01b Remove Option::OutputHHBC and Option::SystemGen 2013-03-21 15:17:33 -07:00
ottoni d996ae0065 Fix HHIR simplification for missing bool-to-int promotions
The simplifier was not promoting the boolean to integer in some
cases. I hit this for the add-zero case, and code inspection revealed
similar bugs in sub-zero and multiply-one cases.
2013-03-21 15:17:24 -07:00
mwilliams 63f228d614 Fix nemo warnings about undefined $this
The fix for the crash caused us to take a different path
when checking locals.
2013-03-21 15:17:24 -07:00
Alex Suhan 903a2444bc Add Awaitable interface
Our PHP code can be simplified by using a common interface
instead of relying on instanceof for proper dispatch.
2013-03-21 15:01:49 -07:00
jdelong 90fa863d44 Put compiler_id in a .cpp file on every link line, remove generated/
Instead of stashing compiler_id in a header that causes rebuilds,
regenerate on every build and list on every link line,
without depending on them.
2013-03-21 14:07:59 -07:00
kma 8c980d31d1 Fix a pair of missing emit*TVType calls.
Reviewing the diff between feature and trunk revealed these two
instructions that still hardcode dwords for types.
2013-03-21 11:31:29 -07:00
jan 2db40741d0 Remove transform_foreach
Iteration opcodes work with locals that are correctly suspended/resumed
thru yield, transform_foreach not needed anymore.
2013-03-21 11:31:29 -07:00
jan 2ebb2a93a1 Eliminate {get,set}NthKid() usage with known specific kid
{get,set}NthKid() should be only used to walk thru all the kids and not to get/set a known specific kid. Replace its use by direct helper method.

All remaining callers of {get,set}NthKid() were audited and there are no instances left accessing specific kid.
2013-03-19 14:11:17 -07:00
bsimmers 3f829f3ede Print relative offsets in Eval.JitCompareHHIR
This diff adds a relativeOffsets option to Disasm, which will print
code addresses as relative offsets from the beginning of the tracelet instead
of absolute addresses. This format makes it much easier to compare the relative
sizes of the instructions selected by the two jits. I also changed the runtime
option to be a double instead of a bool, which is used as the cutoff ratio for
which tracelets to print. Setting it to 1 will print tracelets where the ir
made larger code than tx64, setting it to 2 will print tracelets where the ir's
code is at least twice as big as tx64's, etc...
2013-03-19 14:11:16 -07:00
bsimmers 02e0774721 Implement support for stack bases in VectorTranslator
Any vector instructions that take a pointer to a base and might modify
it are now flagged with MayModifyStack. Any that actually do modify the stack
(this can be determined by looking at the input types) will produe two dests:
their original result and a new StkPtr. getStackValue calls into VectorEffects
to extract the new type and/or value. The instructions currently assume that
the stack cell they might be modifying is already synced to memory. This may
change in the future when we don't have to do a full SpillStack before the
helpers.
2013-03-19 14:11:16 -07:00
bsimmers ea56a8383e Implement specialized array setting in VectorTranslator
This mimics what TranslatorX64 does in translateSetMArray,
but it does it with fewer helpers and (often) fewer instructions in
translated code. I also found a bug in both jits and the interpreter
when dealing with arrays that hold refs to themselves. The new test
case exercises the fix, which involved a bit of refactoring of the
refcounting logic.

Enabling VectorTranslator while punting to tx64 is no longer a
regression so I removed the punt in emit().
2013-03-19 14:11:16 -07:00
smith c3a15af2e5 Re-Tighten live register calculations
Compute the registers that are live across each IR instruction, rather
than the live-out set.  I noticed this while working on a fix for the
CallBuiltin instruction.

We currently compute which registers are live-out from each instruction,
then use the sets to push/pop callee-saved registers around native calls.
cgCallHelper() has a hack to remove destination registers from this set,
but it's not always precise, because we sometimes call cgCallHelper with
different dest registers than were assigned to the instruction, which
(rarely) can cause unnecessary spilling.

In one case cgLdClsMethodFCache(), one of the src tmps is copied to a
destination before the internal call; in that case the dst is not live
across the whole instruction but the value must still be preserved
across the call.  Easy fix: mark it live before cgCallHelper().
2013-03-19 14:11:16 -07:00
Owen Yamauchi 36afbda910 Introduce callee-saved-regs clobber macro
Self-explanatory. The list of callee-saved regs on ARM comes from the
ARMv8 Procedure Call Standard.
2013-03-19 14:11:16 -07:00
alia 9690cc4f52 Fixed problems with HHIR's LdObjMethod instruction
This diff fixes problems with FPushObjMethodD stack unwinding, to HHIR.
This diff simply moves the try-catch into the methodCacheSlowPath.
This should also improve the code generated by gcc for the fast path.
2013-03-19 14:11:11 -07:00
hermanv b3b767d6b2 Initialize local that receives an error code only if there is actually an error.
uidna_openUTS46 overwrites its error code argument only if
there is actually an error. Hence, if the variable is not initialized to
zero it may seem to the calling code that an error has ocurred. This
diff initializes the variable and re-enables the failing test.
2013-03-19 14:11:11 -07:00
mwilliams 63fd7967b2 Fix StringBuffer::resize()
capacity doesnt include the terminating null, so len is
allowed to grow to capacity (not capacity - 1).
2013-03-19 14:11:11 -07:00
mwilliams d8846c5733 Fix assertion when target==analyze
Option::OutputHHBC should always be true.
2013-03-19 14:11:11 -07:00
andrewparoski a8b6ba6962 Implement Tuple
Implement a Tuple class as part of collections.
2013-03-19 14:11:00 -07:00
alia ea03ae9b15 HHIR: Optimized useless incref-decref pairs.
Incref-Decref pairs whose incref'ed SSATmp is not used by any
other instruction other than the decref can be eliminated when the
type of the refcounted value has no destructor (i.e., strings and
boxed strings). This commonly occurs for stores to memory (e.g., SetS,
SetG, and SetM) followed by PopC.

For example:

  47: SetS
    (32) t16:PtrToGen = LdClsPropAddrCached t9:Cls, "s1", "c", Cls(0)
    (33) t17:PtrToCell = UnboxPtr t16:PtrToGen
    (34) t18:Cell = LdMem<Cell> t17:PtrToCell, 0
    (35) t19:Str = IncRef t15:Str
    (36) StMem [t17:PtrToCell]:Str, t15:Str
    (37) DecRef t18:Cell
  48: PopC
    (39) DecRef t19:Str

In this example, eliminating the DecRef instruction (39) along with
its IncRef (35) may cause the string referenced by t19 to be destroyed
earlier in the DecRef instruction (37), but this is safe because
destroying strings has no visible side effects.

This diff eliminates these pairs.

Note that its not safe to do this for types that have destructors with
side effects. Applying this optimization to decref'ed types that have
destructors could change the order of those side effects with respect
to the side effects in instruction (37). A follow-on diff will change
the DecRef (37) to bail the trace when it has to run a destructor to
enable this for the general case.
2013-03-19 13:04:09 -07:00
mwilliams c489379fca Most constructors return null
So annotate the PopR to avoid generating code.
2013-03-19 13:04:09 -07:00
Owen Yamauchi 0323ec38e5 Fix includes in curl_tls_workarounds.cpp
raise_notice() wasn't declared in this file, so include runtime_error.h.
This caused further problems with ATTRIBUTE_PRINTF not being defined
yet, so include some more stuff.
2013-03-19 12:44:39 -07:00
Sara Golemon 1f19c6f051 SSL_OP_NO_TLSv1_2 is not supported by all openssl versions 2013-03-18 18:18:26 -07:00
ottoni 389fa818a9 SIMPLIFY_COMMUTATIVE only handles Type::Int
So check that the inputs are really Ints.
2013-03-18 18:18:26 -07:00
bsimmers 322f6b1b3b Disable test/vm/idn-uts46-errors.php 2013-03-18 18:18:26 -07:00
aravind 647d306c96 Don't simplify Same to Eq to arrays 2013-03-18 18:18:26 -07:00
aravind 42e3a2a7b1 Call IncDecHelper only for Ints 2013-03-18 16:06:01 -07:00
smith 884ff2d218 Use IRExtraData to link ExitTrace[cc] with smashable jumps
Use a new ExitData subclass of IRExtraData to link ExitTrace[Cc]
with the Jmp or Jcc that ends the trace, so the Jmp/Jcc can be
smashed later.  SSATmps should represent runtime values, whereas
these instr->instr pointers are for internal compiler use.
2013-03-18 16:06:01 -07:00
aalexandre 505c17f357 replaced null with uninit_null() 2013-03-18 16:05:53 -07:00
bsimmers 5759bd051b Add assert_throw and assert_log
This diff introduces assert_throw, assert_log, and always_assert_ versions of
the two. They behave similarly to assert, but assert_throw throws a
FailedAssertion exception instead of calling abort. This lets us catch the
exception and add additional debug info to the stacktrace file. In the case of
the IR, this is the current Trace. assert_log takes the condition to check and
a lambda that is expected to return a std::string. If the condition fails, the
lambda will be evaluated and the text returned will be included in the
stacktrace file.

I've left assert_throw off by default so people have to opt into it
locally or in Perflab (see the comment in assert_throw.h)
2013-03-18 15:12:16 -07:00
ottoni e2b5b1f6f4 Eliminate IncRef/DecRef pair when returning a local
In case a tracelet ends with CGetL + RetC, and IncRef/DecRef pair is
generated for the local being returned if it's ref-counted.  The
current ref-count optimization pass was unable to eliminate this, and
this diff tweaks the way HhbcTranslator generates the IR to enable the
optimization to kick in.

Here's the pattern generated without this diff:

CGetL 0
 t0 = LdLoc 0
 t1 = IncRef t0
RetC
 ExitWhenSurprised -> L
 DecRef t0
 RetVal t1
 ...

The source of t0 is not an IncRef, so the optimization doesn't apply.

With this diff, the IR is generated as:

CGetL 0
 t0 = LdLoc 0
 t1 = IncRef t0
RetC
 ExitWhenSurprised -> L
 DecRef t1
 RetVal t0
 ...

This enables the DecRef to be proved non-zero (becoming a DecRefNZ),
so it can be eliminated and the IncRef is sunk to the exit at L.
2013-03-18 15:12:16 -07:00
michalburger1 4858b29f95 Fix bzdecompress
Bad memory allocation, the buffer needs to be large enough to fit all
the data we've decompressed so far plus the extra storage we're
incrementally allocationg, not just the incremental part.
2013-03-18 15:12:16 -07:00
alia 59e537b127 Inlined the fast-path of FPushObjMethodD in the IR.
Inlined the fast-path of FPushObjMethodD in the IR from
MethodCache::lookup. This should reduce the number of times we call
the MethodCache::lookup helper by inlining the common case where the
object's class hits in the target cache.
2013-03-18 15:12:16 -07:00
hermanv 71ea0755d2 use s_self rather than a string literal
Use s_self, s_parent and s_static instead of "self", "parent" and "static" in f_defined.
2013-03-18 15:12:15 -07:00
Sara Golemon 0c912a4d7e Fix typo and timing of setting User-Agent header in http wrapper
$context['user_agent'] was only being respected if
other headers happened to be getting set as well.
Even then, the header being set was "User_Agent" rather than
the correct "User-Agent" version.
2013-03-18 15:12:15 -07:00
Sara Golemon 2027ae7e7e array_keys($arr) and array_keys($arr, NULL) should behave differently
In Zend, the latter form only returns keys which have a NULL
(or NULL-like if $strict==false) value.  The former returns all keys.
2013-03-18 15:12:15 -07:00
Owen Yamauchi f82de49886 Get rid of third-party XHP since it's actually part of the parser 2013-03-18 10:30:25 -07:00
jan 1ecf21f22b ListAssignment: define RHS kind explicitly for all expression types
It's easy to introduce bug by adding a new expression and not defining
its ListAssignment RHS kind. Add all expression types explicitly and
remove default case so that it becomes compile time error if the list is
not updated.
2013-03-15 09:07:36 -07:00
jan e7c6c0cf78 s/m_contTargets/m_controlTargets/ in emitter.{cpp,h}
contTargets name is misleading and suggests it has something to do with
continuations. Rename it to controlTargets.
2013-03-15 09:07:36 -07:00
bsimmers c7b5bbbb34 Fix the release build 2013-03-15 09:07:30 -07:00
bsimmers 0f9b92c2bb Implement known property offsets in VectorTranslator
This diff implements VectorTranslator::emitPropSpecialized and uses it
in three places: emitProp, emitSetProp, and emitCGetProp. The new test case in
test_code_run.cpp used to crash TranslatorX64; now it throws a fatal to keep
things simple. VectorTranslator has better control flow support at its disposal
and is able to get that case right.
2013-03-15 09:07:30 -07:00
bsimmers e580483214 Disable flaky tests in TestExtFile and TestExtImageSprite 2013-03-15 09:07:30 -07:00
smith 5dc84aac72 Remove ffi 2013-03-15 09:06:48 -07:00
kma 82326d7ec8 Access m_type via helpers.
We had the belief that m_type as an int32_t (and in at least one
place, an int64_t) burned in many places. This is going to make any kind of
re-encoding of TypedValues nearly impossible.

Redirect all such accesses via some helpers, so e.g.

        a.  cmpl(KindOfUninit, base[TVOFF(m_type)]);

becomes

       emitCmpTVType(a, KindOfUninit, base[TVOFF(m_type)]);

which may do byte or dword access, depending on m_type's actual size. While
this is motivated by 7pack, I'm planning to route it through trunk to
prevent any more of the old style accesses from cropping up.
2013-03-15 09:04:34 -07:00
mwilliams 6a867726b1 Don't use long double
Slots in the x87 stack get marked as occupied when you move
values into the corresponding mmx registers. If you try
to push a value onto the x87 stack, and the slot isnt empty,
it will fail, and give you a nan.

Generally, g++-x64 doesnt use the x87 instructions, but if
you do long double arithmetic, it does. f_pow was using
long doubles - but there was an alternate, much faster, asm
sequence which didnt use long double, and which just needed
to test the right define - so switch to that. Also grep
for long double to make sure we're not using it elsewhere.
2013-03-15 09:04:34 -07:00
bsimmers d25af371b9 Restore short aliases for DestType enum in nativecalls.cpp
The new names were causing a bunch of merge conflicts and
reduced the signal to noise ratio of the table. This is completely
contained within nativecalls.cpp; the new enum scope is preserved
everywhere else.
2013-03-15 09:04:34 -07:00
smith 693dc1e1be Add new DestType enum for helpers that return TypedValue.
This is necessary because without it, the only clue we have about
what return type a helper has, is the register assignments of the
destination SSATmp.  It is possible that even though the helper returns
a TypedValue, we might only have dest registers assigned for one part
or the other part.

Lastly, we could end up having helpers that return other two-register
results, which shouldn't be confused with TypedValue.

Also fixed cgFCallBuiltin() to use the correct size test
instruction when computing on types.  Types are currnetly 32bits
and the other bits can be garbage.

Renamed ArgGroup.valueType() to typedValue() for clarity.  It's only for
passing TypedValues by value; other register-packed structs would
need new helpers.

Added more asserts in cgCallHelper based on the return type.
assert if we assigned a register but DestType implies there's no
such value (e.g. assigning a void return to a register).
2013-03-14 14:27:22 -07:00
ottoni ba2cf21ec9 Properly patch exit traces ending with JmpZero and JmpNZero
The hoistConditionalJumps pass was not handling traces ending with
JmpZero and JmpNZero.  This was resulting in spurious jumps to
'astubs' instead of patching the jcc+jump pair in 'a'.
2013-03-14 14:27:22 -07:00
mwilliams f7b802c872 Use lookupUniqueClass
The translator does better in a number of places when it
knows an AttrUnqiue Class* at translation time - even if it
doesnt know for sure that it will be defined when we enter the
tracelet. Now that we autoload (nearly) everything, we enter
a lot of tracelets where an AttrUnique Class* has been seen
(during warmup) but is not yet defined (in this request).
I added lookupUniqueClass while working on the new autoloader
to find such Classes, and allow us to do a better translation,
but never got around to using it.
2013-03-14 14:27:22 -07:00
ptarjan bc49d78100 tell closures about scope clones
In HHBC mode, traits are flattened into their classes.
When that happens, closures need to know about all the
classes that contain them so that when we find a ##$this##
inside the closure, it can tell EVERY containing scope to
please propogate ##$this## down to me.
2013-03-14 14:27:22 -07:00
kma 35bd9acebb Minor assembler enhancements. 2013-03-14 14:27:22 -07:00
andrewparoski cc858b73db Collections updates
Replace "collection" with "collections" in various file names since
we typically use the plural form in conversation and documentation.

Add set() and removeAt() methods needed for collection interfaces. Also
add the KeyedIterable and KeyedIterator interfaces.

Add __construct() methods for collections
2013-03-14 14:27:16 -07:00
mwilliams 731a3fcd23 Fix emitInterceptProlog
When the compare was rewritten for the new assembler syntax
it was accidently changed from being a compare of the byte
pointed to by rax, to a compare of the low byte of rax.

I also noticed that by loading the Func* into rax, and doing
a compare against rax[Func::maybeInterceptedOff()] we can
skip a subsequent mov of the Func* into rax.

The code was only slightly broken because we set everything
to be interceptable up front, (if EnableRenameFunction is on)
because we had too many issues with the invalidation code. The
bug was that if the Func happened to be allocated at a multiple
of 256 bytes, it wasnt interceptable.

Also, the existing code looked silly,

  mov  $abcdef45, $eax
  cmp  0, $al

and the new code is smaller.
2013-03-14 11:41:16 -07:00
ottoni a7dc6b461c Reenable direct branch patching for ExitTraceCc
It looks like the pattern-matching performed in
hoistConditionalJumps() was not updated when control-flow support was
added, so the optimization was missing opportunities.
2013-03-14 11:41:16 -07:00
mwilliams b67c2239ed Simplify classof
We dont need to check whether the first Class* is
an interface or trait.

If the second class is an interface or trait, we
take the slow path. Otherwise, we take the fast path,
which will always return false if the first class is
an interface or trait (its m_classVec can only contain
interfaces or traits, while cls's m_classVec can only
contain non-interfaces and non-traits).

This saves doing the check, and avoids the slow path
in the case where the class being tested  is an interface
or trait.
2013-03-14 11:41:16 -07:00
mwilliams 97cf4e0e06 Limit the number of blocks handled by TraceBuilder::optimizeTrace
It appears to be O(N^3) in the number of blocks (a quick glance
at the code suggested N^2, but 1000 blocks took about .5s to process
while 2000 blocks took 4; 19000 blocks was nowhere near finished in
an hour). A better representation of the dominators would probably
solve this - but would also take *much* more space.
Having more than 1000 blocks appears to be extremely rare, so
this seems like a reasonable solution for now.
2013-03-14 11:41:16 -07:00
mwilliams 1678132143 Fix CodeGenerator::cgNInstanceOf
It assumed the result would be in rax, but it isnt always.
Use the correct register.
2013-03-13 09:56:35 -07:00
andrewparoski c1e4c29d0d Some ObjectData/Variant cleanup and dead code removal
This diff eliminates setOpEqual() and appendOpEqual() from Variant, and
it also removes several methods from ObjectData: o_assign_op(), o_argval(),
setDummy(), init(), cloneDynamic(), o_setPublicWithRef(), o_i_set(),
getRedeclaredParent(), and o_propForIteration().

This diff also makes several methods in ObjectData non-virtual: destruct(),
o_toIterArray(), and o_getDynamicProperties(). To achieve this, some of the
logic from Instance was moved to ObjectData.

Finally, this diff gets rid of "hhvm/externals_stubs.cpp" and
"runtime/eval/eval.cpp".
2013-03-13 09:56:28 -07:00
bertrand 97010deac1 Fixed ContNext by writing InitNull rather than Uninit.
Apparently, m_received needs to be InitNull, rather than
Uninit.
2013-03-13 09:53:58 -07:00
mwilliams 4514a79c60 Remove ReqSrc and ReqMod
They can no longer be generated. Also remove all the associated
code from the emitter.
2013-03-13 09:53:58 -07:00
41700 arquivos alterados com 2440242 adições e 894503 exclusões
+10 -13
Ver Arquivo
@@ -1,10 +1,5 @@
*.[oad]
*.hhbc
/bin*-g
/bin*-O
/bin/*.so
/bin/hphp_options
/bin/systemlib.php
.mkdir
hphp.log
@@ -31,31 +26,33 @@ hphp.log
/hphp/runtime/tmp/run
/hphp/runtime/tmp/run.sh
/hphp/runtime/tmp/libtest.so
/hphp/runtime/vm/repo_schema.h
/hphp/hphpi/gen
/hphp/hphpi/hphpi
/hphp/hphp-build-info.cpp
/hphp/hphp-repo-schema.h
/hphp/hhvm/gen
/hphp/hhvm/hhvm
*.ext_hhvm.cpp
*.ext_hhvm.h
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.cpp
/hphp/runtime/ext_hhvm/ext_hhvm_infotabs.h
/hphp/tools/shmw/shmw
/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
install_manifest.txt
/output_gd/
/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
+48
Ver Arquivo
@@ -0,0 +1,48 @@
language: cpp
compiler:
- gcc
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
)
+14
Ver Arquivo
@@ -56,6 +56,20 @@ if(ICU_INCLUDE_DIR AND ICU_LIBRARY)
set(ICU_I18N_FOUND 0)
set(ICU_I18N_LIBRARIES)
endif (ICU_I18N_LIBRARY)
# Look for the ICU data libraries
find_library(
ICU_DATA_LIBRARY
NAMES icudata cygicudata cygicudata32
DOC "Libraries to link against for ICU data")
mark_as_advanced(ICU_DATA_LIBRARY)
if (ICU_DATA_LIBRARY)
set(ICU_DATA_FOUND 1)
set(ICU_DATA_LIBRARIES ${ICU_DATA_LIBRARY})
else (ICU_DATA_LIBRARY)
set(ICU_DATA_FOUND 0)
set(ICU_DATA_LIBRARIES)
endif (ICU_DATA_LIBRARY)
else(ICU_INCLUDE_DIR AND ICU_LIBRARY)
set(ICU_FOUND 0)
set(ICU_I18N_FOUND 0)
+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)
+10 -1
Ver Arquivo
@@ -51,5 +51,14 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibElf DEFAULT_MSG
LIBELF_LIBRARIES
LIBELF_INCLUDE_DIRS)
SET(CMAKE_REQUIRED_LIBRARIES elf)
INCLUDE(CheckCXXSourceCompiles)
CHECK_CXX_SOURCE_COMPILES("#include <libelf.h>
int main() {
Elf *e = (Elf*)0;
size_t sz;
elf_getshdrstrndx(e, &sz);
return 0;
}" ELF_GETSHDRSTRNDX)
mark_as_advanced(LIBELF_INCLUDE_DIRS LIBELF_LIBRARIES)
mark_as_advanced(LIBELF_INCLUDE_DIRS LIBELF_LIBRARIES ELF_GETSHDRSTRNDX)
+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)
+1 -1
Ver Arquivo
@@ -29,7 +29,7 @@
#-------------- FIND MYSQL_INCLUDE_DIR ------------------
FIND_PATH(MYSQL_INCLUDE_DIR mysql/mysql.h
FIND_PATH(MYSQL_INCLUDE_DIR mysql.h
$ENV{MYSQL_INCLUDE_DIR}
$ENV{MYSQL_DIR}/include
/usr/include/mysql
+27
Ver Arquivo
@@ -0,0 +1,27 @@
# - Try to find libpthread
#
# Once done this will define
#
# LIBPTHREAD_FOUND - system has libpthread
# LIBPTHREAD_INCLUDE_DIRS - the libpthread include directory
# LIBPTHREAD_LIBRARIES - Link these to use libpthread
# LIBPTHREAD_DEFINITIONS - Compiler switches required for using libpthread
#
# Redistribution and use is allowed according to the terms of the New
# BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
#
if (LIBPTHREAD_LIBRARIES AND LIBPTHREAD_INCLUDE_DIRS)
set (LIBPTHREAD_FIND_QUIETLY TRUE)
endif (LIBPTHREAD_LIBRARIES AND LIBPTHREAD_INCLUDE_DIRS)
find_path (LIBPTHREAD_INCLUDE_DIRS NAMES pthread.h)
find_library (LIBPTHREAD_LIBRARIES NAMES pthread)
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBPTHREAD DEFAULT_MSG
LIBPTHREAD_LIBRARIES LIBPTHREAD_INCLUDE_DIRS)
mark_as_advanced(LIBPTHREAD_INCLUDE_DIRS LIBPTHREAD_LIBRARIES LIBPTHREAD_FOUND)
+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()
+158 -71
Ver Arquivo
@@ -17,11 +17,25 @@
include(CheckFunctionExists)
# boost checks
# 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)
@@ -39,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})
@@ -80,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
@@ -138,16 +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")
FIND_LIBRARY(XHP_LIB xhp)
FIND_PATH(XHP_INCLUDE_DIR xhp_preprocess.hpp)
if (XHP_LIB AND XHP_INCLUDE_DIR)
include_directories(${XHP_INCLUDE_DIR})
set(SKIP_BUNDLED_XHP ON)
else()
include_directories("${HPHP_HOME}/hphp/third_party/xhp/xhp")
endif()
include_directories("${HPHP_HOME}/hphp/third_party/libzip")
# ICU
find_package(ICU REQUIRED)
@@ -161,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)
@@ -188,17 +203,35 @@ if (USE_GOOGLE_HEAP_PROFILER AND GOOGLE_PROFILER_LIB)
endif()
endif()
if (USE_JEMALLOC AND NOT GOOGLE_TCMALLOC_ENABLED
AND NOT CMAKE_BUILD_TYPE STREQUAL Debug)
FIND_LIBRARY(JEMALLOC_LIB jemalloc)
if (JEMALLOC_LIB)
message(STATUS "Found jemalloc: ${JEMALLOC_LIB}")
set(JEMALLOC_ENABLED 1)
if (USE_JEMALLOC AND NOT GOOGLE_TCMALLOC_ENABLED)
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()
if (USE_TCMALLOC AND NOT JEMALLOC_ENABLED AND NOT GOOGLE_TCMALLOC_ENABLED
AND NOT CMAKE_BUILD_TYPE STREQUAL Debug)
if (USE_TCMALLOC AND NOT JEMALLOC_ENABLED AND NOT GOOGLE_TCMALLOC_ENABLED)
FIND_LIBRARY(GOOGLE_TCMALLOC_MIN_LIB tcmalloc_minimal)
if (GOOGLE_TCMALLOC_MIN_LIB)
message(STATUS "Found minimal tcmalloc: ${GOOGLE_TCMALLOC_MIN_LIB}")
@@ -265,17 +298,36 @@ include_directories(${LDAP_INCLUDE_DIR})
find_package(Ncurses REQUIRED)
include_directories(${NCURSES_INCLUDE_PATH})
find_package(Readline REQUIRED)
include_directories(${READLINE_INCLUDE_DIR})
# libpthreads
find_package(PThread REQUIRED)
include_directories(${LIBPTHREAD_INCLUDE_DIRS})
# 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})
if (ELF_GETSHDRSTRNDX)
add_definitions("-DHAVE_ELF_GETSHDRSTRNDX")
endif()
CONTAINS_STRING("${CCLIENT_INCLUDE_PATH}/utf8.h" U8T_DECOMPOSE RECENT_CCLIENT)
if (NOT RECENT_CCLIENT)
@@ -283,29 +335,35 @@ 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)
add_definitions(-DSKIP_IMAP_SSL=1)
endif()
FIND_LIBRARY(CRYPT_LIB NAMES xcrypt crypt crypto)
if (LINUX OR FREEBSD)
FIND_LIBRARY (CRYPT_LIB NAMES xcrypt crypt)
FIND_LIBRARY (RT_LIB rt)
elseif (APPLE)
FIND_LIBRARY (CRYPT_LIB crypto)
FIND_LIBRARY (ICONV_LIB iconv)
endif()
if (LINUX)
@@ -339,6 +397,14 @@ if (FREEBSD)
endif()
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()
#find_package(BISON REQUIRED)
#find_package(FLEX REQUIRED)
@@ -350,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()
@@ -365,10 +435,9 @@ 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_LIBRARIES} ${ICU_I18N_LIBRARIES})
target_link_libraries(${target} ${ICU_DATA_LIBRARIES} ${ICU_I18N_LIBRARIES} ${ICU_LIBRARIES})
target_link_libraries(${target} ${LIBEVENT_LIB})
target_link_libraries(${target} ${CURL_LIBRARIES})
target_link_libraries(${target} ${LIBGLOG_LIBRARY})
@@ -399,9 +468,16 @@ if (FREEBSD)
target_link_libraries(${target} ${EXECINFO_LIB})
endif()
if (APPLE)
target_link_libraries(${target} ${LIBINTL_LIBRARIES})
target_link_libraries(${target} ${KERBEROS_LIB})
endif()
target_link_libraries(${target} ${BFD_LIB})
target_link_libraries(${target} ${BINUTIL_LIB})
target_link_libraries(${target} pthread)
if (${LIBPTHREAD_LIBRARIES})
target_link_libraries(${target} ${LIBPTHREAD_LIBRARIES})
endif()
target_link_libraries(${target} ${TBB_LIBRARIES})
target_link_libraries(${target} ${OPENSSL_LIBRARIES})
target_link_libraries(${target} ${ZLIB_LIBRARIES})
@@ -412,18 +488,29 @@ 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})
target_link_libraries(${target} ${LIBMEMCACHED_LIBRARY})
target_link_libraries(${target} ${CRYPT_LIB})
if (LINUX OR FREEBSD)
target_link_libraries(${target} ${CRYPT_LIB})
target_link_libraries(${target} ${RT_LIB})
elseif (APPLE)
target_link_libraries(${target} ${CRYPTO_LIB})
target_link_libraries(${target} ${ICONV_LIB})
endif()
target_link_libraries(${target} timelib)
@@ -431,21 +518,21 @@ endif()
target_link_libraries(${target} lz4)
target_link_libraries(${target} double-conversion)
target_link_libraries(${target} folly)
if (SKIP_BUNDLED_XHP)
target_link_libraries(${target} ${XHP_LIB})
else()
target_link_libraries(${target} xhp)
endif()
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()
+69 -67
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 < 40400
#error Need GCC 4.4.0+
#endif
int main() { return 0; }" HAVE_GCC_44)
if(NOT HAVE_GCC_44)
message(FATAL_ERROR "Need at least GCC 4.4")
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,15 @@ if(APPLE)
endif()
endif()
include(HPHPCompiler)
include(HPHPFunctions)
include(HPHPFindLibs)
add_definitions(-D_GNU_SOURCE -D_REENTRANT=1 -D_PTHREADS=1)
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)
endif()
if(${CMAKE_BUILD_TYPE} MATCHES "Release")
add_definitions(-DRELEASE=1)
@@ -57,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()
@@ -89,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()
@@ -105,31 +105,33 @@ if(APPLE OR FREEBSD)
add_definitions(-DSKIP_USER_CHANGE=1)
endif()
if(APPLE)
# We have to be a little more permissive in some cases.
add_definitions(-fpermissive)
# Skip deprecation warnings in OpenSSL.
add_definitions(-DMAC_OS_X_VERSION_MIN_REQUIRED=MAC_OS_X_VERSION_10_6)
# Just assume we have sched.h
add_definitions(-DFOLLY_HAVE_SCHED_H=1)
# Enable weak linking
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)
execute_process(COMMAND git describe --all --long --abbrev=40 --always
OUTPUT_VARIABLE _COMPILER_ID OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
if (_COMPILER_ID)
add_definitions(-DCOMPILER_ID="${_COMPILER_ID}")
endif()
IF($ENV{CXX} MATCHES "icpc")
set(CMAKE_C_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -w")
set(CMAKE_CXX_FLAGS "-no-ipo -fp-model precise -wd584 -wd1418 -wd1918 -wd383 -wd869 -wd981 -wd424 -wd1419 -wd444 -wd271 -wd2259 -wd1572 -wd1599 -wd82 -wd177 -wd593 -fno-omit-frame-pointer -ftemplate-depth-120 -Wall -Woverloaded-virtual -Wno-deprecated -w1 -Wno-strict-aliasing -Wno-write-strings -Wno-invalid-offsetof -fno-operator-names")
else()
set(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()
# later versions of binutils don't play well without automake
add_definitions(-DPACKAGE=hhvm -DPACKAGE_VERSION=Release)
include_directories(${HPHP_HOME}/hphp)
include_directories(${HPHP_HOME}/hphp/lib/system/gen)
+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)
+12 -22
Ver Arquivo
@@ -1,18 +1,18 @@
CMAKE_MINIMUM_REQUIRED(VERSION 2.6.4 FATAL_ERROR)
PROJECT(hphp C CXX)
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)
+26 -58
Ver Arquivo
@@ -1,78 +1,46 @@
# HipHop for PHP
# HHVM [![Build Status](https://travis-ci.org/facebook/hhvm.png?branch=master)](https://travis-ci.org/facebook/hhvm)
HipHop is a high performance PHP toolchain. Currently supported platforms are Linux and FreeBSD. There is no OS X support.
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.
* [Developer Mailing List](http://groups.google.com/group/hiphop-php-dev)
* [Wiki](http://wiki.github.com/facebook/hiphop-php)
* [Issue Tracker](http://github.com/facebook/hiphop-php/issues)
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.
## Required Packages
## FAQ
The latest information is available on the [wiki](http://wiki.github.com/facebook/hiphop-php/building-and-installing)
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.
* cmake *2.6 is the minimum version*
* g++/gcc *4.3 is the minimum version*
* Boost *1.37 is the minimum version*
* flex
* bison
* re2c
* libmysql
* libxml2
* libmcrypt
* libicu *4.2 is the minimum version*
* openssl
* binutils
* libcap
* gd
* zlib
* tbb *Intel's Thread Building Blocks*
* [Oniguruma](http://www.geocities.jp/kosako3/oniguruma/)
* libpcre
* libexpat
* libmemcached
* google-glog (http://code.google.com/p/google-glog/)
* libc-client2007
* libdwarf
* libelf
* libunwind
## Installing
The following packages have had slight modifications added to them. Patches are provided and should be made against the current source copies.
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).
* [libcurl](http://curl.haxx.se/download.html)
* hphp/third_party/libcurl.fb-changes.diff
* [libevent 1.4](http://www.monkey.org/~provos/libevent/)
* hphp/third_party/libevent-1.4.14.fb-changes.diff
## Running
## Installation
You can run standalone programs just by passing them to hhvm: `hhvm my_script.php`.
You may need to point CMake to the location of your custom libcurl and libevent, or to any other libraries which needed to be installed. The *CMAKE_PREFIX_PATH* variable is used to hint to the location.
HHVM bundles in a webserver. So if you want to run on port 80 in the current directory:
export CMAKE_PREFIX_PATH=/home/user
```
sudo hhvm -m server
```
To build HipHop, use the following:
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`.
Linux:
## Contributing
cd /home/user/dev
git clone git://github.com/facebook/hiphop-php.git
cd hiphop-php
git submodule init
git submodule update
export HPHP_HOME=`pwd`
export HPHP_LIB=`pwd`/bin
cmake .
We'd love to have your help in making HHVM better.
If you are using FreeBSD instead use export - setenv
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.
Once this is done you can generate the build file. This will return you to the shell. Finally, to build, run `make`. If any errors occur, it may be required to remove the CMakeCache.txt directory in the checkout.
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).
make
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.
## Contributing to HipHop
HipHop is licensed under the PHP and Zend licenses except as otherwise noted.
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.
Before changes can be accepted a [Contributors Licensing Agreement](http://developers.facebook.com/opensource/cla) must be signed and returned.
## Running HipHop
## License
Please see [the wiki page](http://wiki.github.com/facebook/hiphop-php/running-hiphop)
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.
-5579
Ver Arquivo
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
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
Arquivo executável
+126
Ver Arquivo
@@ -0,0 +1,126 @@
#########################################
#
# Install all the dependencies for HipHop
#
#########################################
SCRIPT_NAME='./configure_ubuntu_12.04.sh'
if [ "$0" != "$SCRIPT_NAME" ]; then
echo "Run the script from the hiphop-php directory like:"
echo " $SCRIPT_NAME"
exit 1
fi
if [ "x${TRAVIS}" != "x" ]; then
# Collect some stats for use in tuning build later on
free
CPUS=`cat /proc/cpuinfo | grep -E '^processor' | tail -1 | cut -d : -f 2`
CPUS=`expr ${CPUS} + 1`
echo "CPUs: ${CPUS}"
fi
export CMAKE_PREFIX_PATH=`/bin/pwd`/..
# 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 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 &
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
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 -j $CPUS
make install
cd ..
# curl
cd curl
./buildconf
./configure --prefix=$CMAKE_PREFIX_PATH
make -j $CPUS
make install
cd ..
# glog
cd google-glog
./configure --prefix=$CMAKE_PREFIX_PATH
make -j $CPUS
make install
cd ..
# jemaloc
tar xjvf jemalloc-3.0.0.tar.bz2
cd jemalloc-3.0.0
./configure --prefix=$CMAKE_PREFIX_PATH
make -j $CPUS
make install
cd ..
# cleanup
rm -rf libevent curl google-glog jemalloc-3.0.0.tar.bz2 jemalloc-3.0.0
# hphp
cmake .
echo "-------------------------------------------------------------------------"
echo "Done. Now run:"
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 -76
Ver Arquivo
@@ -16,58 +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/eval runtime/ext runtime/vm system 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})
endforeach(dir ${RECURSIVE_SOURCE_SUBDIRS})
# Disable hardware counters off of Linux
if(NOT LINUX)
add_definitions(-DNO_HARDWARE_COUNTERS)
list(REMOVE_ITEM CXX_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/runtime/base/hardware_counter.cpp)
endif()
# remove ext_hhvm, util/tests, and runtime/vm/translator/test
foreach (file ${CXX_SOURCES})
if (${file} MATCHES "ext_hhvm")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
if (${file} MATCHES "util/test")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
if (${file} MATCHES "runtime/vm/translator/test")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
if (${file} MATCHES "runtime/vm/translator/hopt/test")
list(REMOVE_ITEM CXX_SOURCES ${file})
endif()
endforeach(file ${CXX_SOURCES})
# remove ext/sep for hhvm
foreach (file ${CXX_SOURCES})
if (${file} MATCHES "ext/sep")
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")
if (NOT SKIP_BUNDLED_XHP)
add_subdirectory(third_party/xhp/xhp)
endif()
add_subdirectory(tools/bootstrap)
add_subdirectory(third_party/libafdt)
add_subdirectory(third_party/libmbfl)
@@ -76,38 +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 runtime/vm/repo_schema.h
COMMAND hphp/tools/generate_repo_schema.sh
DEPENDS ${CXX_SOURCES} ${C_SOURCES}
WORKING_DIRECTORY ${HPHP_HOME}
COMMENT "Generating Repo Schema ID"
VERBATIM)
ADD_LIBRARY(hphp_runtime_static STATIC runtime/vm/repo_schema.h ${CXX_SOURCES} ${C_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(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(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)
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+9 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,10 +14,10 @@
+----------------------------------------------------------------------+
*/
#ifndef __ALIAS_MANAGER_H__
#define __ALIAS_MANAGER_H__
#ifndef incl_HPHP_ALIAS_MANAGER_H_
#define incl_HPHP_ALIAS_MANAGER_H_
#include <compiler/expression/expression.h>
#include "hphp/compiler/expression/expression.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -88,7 +88,7 @@ class AliasManager {
enum { SameAccess, SameLValueAccess, InterfAccess,
DisjointAccess, NotAccess };
AliasManager(int opt);
explicit AliasManager(int opt);
~AliasManager();
void clear();
@@ -141,7 +141,7 @@ class AliasManager {
enum { FallThrough, CondBranch, Branch, Converge };
enum { NoCopyProp = 1, NoDeadStore = 2 };
struct CondStackElem {
CondStackElem(size_t s = 0) : m_size(s), m_exprs() {}
explicit CondStackElem(size_t s = 0) : m_size(s), m_exprs() {}
size_t m_size;
ExpressionPtrList m_exprs;
};
@@ -154,7 +154,7 @@ class AliasManager {
class LoopInfo {
public:
LoopInfo(StatementPtr s);
explicit LoopInfo(StatementPtr s);
StatementPtr m_stmt;
StatementPtrVec m_inner;
@@ -205,7 +205,7 @@ class AliasManager {
StatementPtr canonicalizeRecur(StatementPtr e, int &ret);
void invalidateChainRoots(StatementPtr s);
void nullSafeDisableCSE(StatementPtr parent, int kid);
void nullSafeDisableCSE(StatementPtr parent, ExpressionPtr kid);
void disableCSE(StatementPtr s);
void createCFG(MethodStatementPtr m);
void deleteCFG();
@@ -276,4 +276,4 @@ class AliasManager {
///////////////////////////////////////////////////////////////////////////////
}
#endif // __ALIAS_MANAGER_H__
#endif // incl_HPHP_ALIAS_MANAGER_H_
+226 -135
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,45 +14,48 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/analysis_result.h"
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <boost/format.hpp>
#include <boost/bind.hpp>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/depth_first_visitor.h>
#include <compiler/statement/statement_list.h>
#include <compiler/statement/if_branch_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/loop_statement.h>
#include <compiler/statement/class_variable.h>
#include <compiler/statement/use_trait_statement.h>
#include <compiler/analysis/symbol_table.h>
#include <compiler/package.h>
#include <compiler/parser/parser.h>
#include <compiler/option.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/builtin_symbols.h>
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/expression/constant_expression.h>
#include <compiler/expression/expression_list.h>
#include <compiler/expression/array_pair_expression.h>
#include <runtime/ext/ext_json.h>
#include <runtime/base/zend/zend_printf.h>
#include <runtime/base/program_functions.h>
#include <util/atomic.h>
#include <util/logger.h>
#include <util/util.h>
#include <util/hash.h>
#include <util/process.h>
#include <util/job_queue.h>
#include <util/timer.h>
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/depth_first_visitor.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/statement/if_branch_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#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"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#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-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/timer.h"
using namespace HPHP;
using std::map;
@@ -157,6 +160,10 @@ void AnalysisResult::parseOnDemandBy(const string &name,
}
}
void AnalysisResult::addNSFallbackFunc(ConstructPtr c, FileScopePtr fs) {
m_nsFallbackFuncs.insert(std::make_pair(c, fs));
}
FileScopePtr AnalysisResult::findFileScope(const std::string &name) const {
StringToFileScopePtrMap::const_iterator iter = m_files.find(name);
if (iter != m_files.end()) {
@@ -169,7 +176,7 @@ FunctionScopePtr AnalysisResult::findFunction(
const std::string &funcName) const {
StringToFunctionScopePtrMap::const_iterator bit =
m_functions.find(funcName);
if (bit != m_functions.end()) {
if (bit != m_functions.end() && !bit->second->allowOverride()) {
return bit->second;
}
StringToFunctionScopePtrMap::const_iterator iter =
@@ -177,7 +184,7 @@ FunctionScopePtr AnalysisResult::findFunction(
if (iter != m_functionDecs.end()) {
return iter->second;
}
return FunctionScopePtr();
return bit != m_functions.end() ? bit->second : FunctionScopePtr();
}
BlockScopePtr AnalysisResult::findConstantDeclarer(
@@ -235,8 +242,8 @@ ClassScopePtr AnalysisResult::findClass(const std::string &name,
return ClassScopePtr();
}
const ClassScopePtrVec &AnalysisResult::findRedeclaredClasses
(const std::string &name) const {
const ClassScopePtrVec &
AnalysisResult::findRedeclaredClasses(const std::string &name) const {
StringToClassScopePtrVecMap::const_iterator iter = m_classDecs.find(name);
if (iter == m_classDecs.end()) {
static ClassScopePtrVec empty;
@@ -343,11 +350,14 @@ bool AnalysisResult::declareFunction(FunctionScopePtr funcScope) const {
string fname = funcScope->getName();
// System functions override
if (m_functions.find(fname) != m_functions.end()) {
// we need someone to hold on to a reference to it
// even though we're not going to do anything with it
this->lock()->m_ignoredScopes.push_back(funcScope);
return false;
auto it = m_functions.find(fname);
if (it != m_functions.end()) {
if (!it->second->allowOverride()) {
// we need someone to hold on to a reference to it
// even though we're not going to do anything with it
this->lock()->m_ignoredScopes.push_back(funcScope);
return false;
}
}
return true;
@@ -399,7 +409,9 @@ static bool by_source(const BlockScopePtr &b1, const BlockScopePtr &b2) {
void AnalysisResult::canonicalizeSymbolOrder() {
getConstants()->canonicalizeSymbolOrder();
getVariables()->canonicalizeSymbolOrder();
}
void AnalysisResult::markRedeclaringClasses() {
AnalysisResultPtr ar = shared_from_this();
for (StringToClassScopePtrVecMap::iterator iter = m_classDecs.begin();
iter != m_classDecs.end(); ++iter) {
@@ -411,6 +423,56 @@ void AnalysisResult::canonicalizeSymbolOrder() {
}
}
}
auto markRedeclaring = [&] (const std::string& name) {
auto it = m_classDecs.find(name);
if (it != m_classDecs.end()) {
auto& classes = it->second;
for (unsigned int i = 0; i < classes.size(); ++i) {
classes[i]->setRedeclaring(ar, i);
}
}
};
/*
* In WholeProgram mode, during parse time we collected all
* class_alias calls so we can mark the targets of such calls
* redeclaring if necessary.
*
* Two cases here that definitely require this:
*
* - If an alias name has the same name as another class, we need
* to mark *that* class as redeclaring, since it may mean
* different things in different requests now.
*
* - If an alias name can refer to more than one class, each of
* those classes must be marked redeclaring.
*
* In the simple case of a unique alias name and a unique target
* name, we might be able to get away with manipulating the target
* classes' volatility.
*
* Rather than work through the various cases here, though, we've
* just decided to just play it safe and mark all the names involved
* as redeclaring for now.
*/
for (auto& kv : m_classAliases) {
assert(kv.first == Util::toLower(kv.first));
assert(kv.second == Util::toLower(kv.second));
markRedeclaring(kv.first);
markRedeclaring(kv.second);
}
/*
* Similar to class_alias, when a type alias is declared with the
* same name as a class in the program, we need to make sure the
* class is marked redeclaring. It is possible in some requests
* that things like 'instanceof Foo' will not mean the same thing.
*/
for (auto& name : m_typeAliasNames) {
assert(Util::toLower(name) == name);
markRedeclaring(name);
}
}
///////////////////////////////////////////////////////////////////////////////
@@ -427,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 =
@@ -446,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);
@@ -509,17 +569,16 @@ bool AnalysisResult::isSystemConstant(const std::string &constName) const {
///////////////////////////////////////////////////////////////////////////////
// Program
void AnalysisResult::loadBuiltinFunctions() {
AnalysisResultPtr ar = shared_from_this();
BuiltinSymbols::LoadFunctions(ar, m_functions);
void AnalysisResult::addSystemFunction(FunctionScopeRawPtr fs) {
FunctionScopePtr& entry = m_functions[fs->getName()];
assert(!entry);
entry = fs;
}
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::addSystemClass(ClassScopeRawPtr cs) {
ClassScopePtr& entry = m_systemClasses[cs->getName()];
assert(!entry);
entry = cs;
}
void AnalysisResult::checkClassDerivations() {
@@ -530,30 +589,49 @@ void AnalysisResult::checkClassDerivations() {
BOOST_FOREACH(cls, iter->second) {
hphp_string_iset seen;
cls->checkDerivation(ar, seen);
if (Option::WholeProgram || !Option::OutputHHBC) {
cls->importUsedTraits(ar);
if (Option::WholeProgram) {
try {
cls->importUsedTraits(ar);
} catch (const AnalysisTimeFatalException& e) {
cls->setFatal(e);
}
}
}
}
}
void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
const StringToFunctionScopePtrMap &funcs = fs->getFunctions();
void AnalysisResult::resolveNSFallbackFuncs() {
for (auto &pair : m_nsFallbackFuncs) {
SimpleFunctionCallPtr sfc =
static_pointer_cast<SimpleFunctionCall>(pair.first);
sfc->resolveNSFallbackFunc(
shared_from_this(),
pair.second
);
}
}
for (StringToFunctionScopePtrMap::const_iterator iter = funcs.begin();
iter != funcs.end(); ++iter) {
FunctionScopePtr func = iter->second;
void AnalysisResult::collectFunctionsAndClasses(FileScopePtr fs) {
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;
}
@@ -561,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++);
@@ -580,12 +657,15 @@ 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(),
fs->getClassAliases().end());
m_typeAliasNames.insert(fs->getTypeAliasNames().begin(),
fs->getTypeAliasNames().end());
}
static bool by_filename(const FileScopePtr &f1, const FileScopePtr &f2) {
@@ -611,6 +691,8 @@ void AnalysisResult::analyzeProgram(bool system /* = false */) {
// Keep generated code identical without randomness
canonicalizeSymbolOrder();
markRedeclaringClasses();
// Analyze some special cases
for (set<string>::const_iterator it = Option::VolatileClasses.begin();
it != Option::VolatileClasses.end(); ++it) {
@@ -621,6 +703,7 @@ void AnalysisResult::analyzeProgram(bool system /* = false */) {
}
checkClassDerivations();
resolveNSFallbackFuncs();
// Analyze All
Logger::Verbose("Analyzing All");
@@ -660,7 +743,7 @@ void AnalysisResult::analyzeProgram(bool system /* = false */) {
for (StringToFunctionScopePtrMap::const_iterator iterMethod =
methods.begin(); iterMethod != methods.end(); ++iterMethod) {
FunctionScopePtr func = iterMethod->second;
if (!func->hasImpl() && needAbstractMethodImpl) {
if (Option::WholeProgram && !func->hasImpl() && needAbstractMethodImpl) {
FunctionScopePtr tmpFunc =
cls->findFunction(ar, func->getName(), true, true);
always_assert(!tmpFunc || !tmpFunc->hasImpl());
@@ -779,8 +862,14 @@ void AnalysisResult::analyzeProgramFinal() {
for (uint i = 0; i < m_fileScopes.size(); i++) {
m_fileScopes[i]->analyzeProgram(ar);
}
// Keep generated code identical without randomness
canonicalizeSymbolOrder();
// XXX: this is only here because canonicalizeSymbolOrder used to do
// it---is it necessary to repeat at this phase? (Probably not ...)
markRedeclaringClasses();
setPhase(AnalysisResult::CodeGen);
}
@@ -853,9 +942,11 @@ struct OptVisitor {
OptVisitor(AnalysisResultPtr ar, unsigned nscope) :
m_ar(ar), m_nscope(nscope), m_dispatcher(0) {
}
OptVisitor(const Visitor &po) : m_ar(po.m_ar),
m_nscope(po.m_nscope),
m_dispatcher(po.m_dispatcher) {
/* implicit */ OptVisitor(const Visitor &po)
: m_ar(po.m_ar)
, m_nscope(po.m_nscope)
, m_dispatcher(po.m_dispatcher)
{
const_cast<Visitor&>(po).m_dispatcher = 0;
}
~OptVisitor() {
@@ -884,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() {}
@@ -900,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);
@@ -960,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);
@@ -1002,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);
@@ -1026,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);
@@ -1071,12 +1165,12 @@ typedef OptWorker<Post> PostOptWorker;
template<>
void OptWorker<Pre>::onThreadEnter() {
if (!Option::SystemGen) hphp_session_init();
hphp_session_init();
}
template<>
void OptWorker<Pre>::onThreadExit() {
if (!Option::SystemGen) hphp_session_exit();
hphp_session_exit();
}
/**
@@ -1097,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)
@@ -1142,7 +1236,7 @@ template <typename When>
void
AnalysisResult::preWaitCallback(bool first,
const BlockScopeRawPtrQueue &scopes,
void *opaque) {
void *context) {
// default is no-op
}
@@ -1151,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;
@@ -1216,7 +1310,7 @@ struct BIPairCmp {
template <typename When>
void
AnalysisResult::processScopesParallel(const char *id,
void *opaque /* = NULL */) {
void *context /* = NULL */) {
BlockScopeRawPtrQueue scopes;
getScopesSet(scopes);
@@ -1253,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
{
@@ -1307,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();
@@ -1436,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);
}
@@ -1453,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) {
@@ -1479,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: " <<
@@ -1510,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 */
@@ -1521,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
@@ -1537,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);
}
}
@@ -1585,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());
}
@@ -1599,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;
@@ -1627,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);
+71 -35
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,19 +14,20 @@
+----------------------------------------------------------------------+
*/
#ifndef __ANALYSIS_RESULT_H__
#define __ANALYSIS_RESULT_H__
#ifndef incl_HPHP_ANALYSIS_RESULT_H_
#define incl_HPHP_ANALYSIS_RESULT_H_
#include <compiler/code_generator.h>
#include <compiler/analysis/code_error.h>
#include <compiler/option.h>
#include <compiler/analysis/block_scope.h>
#include <compiler/analysis/symbol_table.h>
#include <compiler/analysis/function_container.h>
#include <compiler/package.h>
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/block_scope.h"
#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 <util/string_bag.h>
#include <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>
@@ -36,7 +37,7 @@ namespace HPHP {
DECLARE_BOOST_TYPES(ClassScope);
DECLARE_BOOST_TYPES(FileScope);
DECLARE_EXTENDED_BOOST_TYPES(FileScope);
DECLARE_BOOST_TYPES(FunctionScope);
DECLARE_BOOST_TYPES(Location);
DECLARE_BOOST_TYPES(AnalysisResult);
@@ -91,12 +92,12 @@ public:
class Locker {
public:
Locker(const AnalysisResult *ar) :
explicit Locker(const AnalysisResult *ar) :
m_ar(const_cast<AnalysisResult*>(ar)),
m_mutex(m_ar->getMutex()) {
m_mutex.lock();
}
Locker(AnalysisResultConstPtr ar) :
explicit Locker(AnalysisResultConstPtr ar) :
m_ar(const_cast<AnalysisResult*>(ar.get())),
m_mutex(m_ar->getMutex()) {
m_mutex.lock();
@@ -148,8 +149,10 @@ public:
void addEntryPoint(const std::string &name);
void addEntryPoints(const std::vector<std::string> &names);
void loadBuiltinFunctions();
void loadBuiltins();
void addNSFallbackFunc(ConstructPtr c, FileScopePtr fs);
void addSystemFunction(FunctionScopeRawPtr fs);
void addSystemClass(ClassScopeRawPtr cs);
void analyzeProgram(bool system = false);
void analyzeIncludes();
void analyzeProgramFinal();
@@ -236,12 +239,22 @@ public:
ClassScopePtr findClass(const std::string &className) const;
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.
*/
const ClassScopePtrVec &findRedeclaredClasses(
const std::string &className) const;
/**
* Find all the classes by the name, including system classes.
*/
@@ -296,10 +309,12 @@ public:
void addNamedScalarVarArray(const std::string &s);
StringToClassScopePtrVecMap getExtensionClasses();
void addInteger(int64_t n);
private:
Package *m_package;
bool m_parseOnDemand;
std::vector<std::string> m_parseOnDemandDirs;
std::set<std::pair<ConstructPtr, FileScopePtr> > m_nsFallbackFuncs;
Phase m_phase;
StringToFileScopePtrMap m_files;
FileScopePtrVec m_fileScopes;
@@ -315,6 +330,13 @@ private:
StringToFileScopePtrMap m_constDecs;
std::set<std::string> m_constRedeclared;
// Map names of class aliases to the class names they will alias.
// Only in WholeProgram mode. See markRedeclaringClasses.
std::multimap<std::string,std::string> m_classAliases;
// Names of type aliases.
std::set<std::string> m_typeAliasNames;
bool m_classForcedVariants[2];
StatementPtrVec m_stmts;
@@ -323,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());
}
@@ -348,6 +370,11 @@ private:
*/
bool inParseOnDemandDirs(const std::string &filename) const;
/*
* Find the names of all functions and classes in the program; mark
* functions with duplicate names as redeclaring, but duplicate
* classes aren't yet marked. See markRedeclaringClasses.
*/
void collectFunctionsAndClasses(FileScopePtr fs);
/**
@@ -356,12 +383,21 @@ private:
*/
void canonicalizeSymbolOrder();
/*
* After all the class names have been collected and symbol order is
* canonicalized, this passes through and marks duplicate class
* names as redeclaring.
*/
void markRedeclaringClasses();
/**
* Checks circular class derivations that can cause stack overflows for
* subsequent analysis. Also checks to make sure no two redundant parents.
*/
void checkClassDerivations();
void resolveNSFallbackFuncs();
int getFileSize(FileScopePtr fs);
public:
@@ -370,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:
@@ -399,13 +435,13 @@ private:
class RescheduleException : public Exception {
public:
RescheduleException(BlockScopeRawPtr scope) :
explicit RescheduleException(BlockScopeRawPtr scope) :
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;
@@ -413,7 +449,7 @@ private:
class SetCurrentScope {
public:
SetCurrentScope(BlockScopeRawPtr scope) {
explicit SetCurrentScope(BlockScopeRawPtr scope) {
assert(!((*AnalysisResult::s_currentScopeThreadLocal).get()));
*AnalysisResult::s_currentScopeThreadLocal = scope;
scope->setInVisitScopes(true);
@@ -499,9 +535,9 @@ private:
}
}
#else
BaseTryLock(BlockScopeRawPtr scopeToLock,
bool lockCondition = true,
bool profile = true)
explicit BaseTryLock(BlockScopeRawPtr scopeToLock,
bool lockCondition = true,
bool profile = true)
: m_profiler(profile),
m_mutex(scopeToLock->getInferTypesMutex()),
m_acquired(false) {
@@ -536,8 +572,8 @@ public:
bool profile = true) :
BaseTryLock(scopeToLock, fromFunction, fromLine, true, profile) {}
#else
TryLock(BlockScopeRawPtr scopeToLock,
bool profile = true) :
explicit TryLock(BlockScopeRawPtr scopeToLock,
bool profile = true) :
BaseTryLock(scopeToLock, true, profile) {}
#endif /* HPHP_INSTRUMENT_TYPE_INF */
};
@@ -595,4 +631,4 @@ public:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __ANALYSIS_RESULT_H__
#endif // incl_HPHP_ANALYSIS_RESULT_H_
+6 -6
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,8 +14,8 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/ast_walker.h>
#include <compiler/statement/statement.h>
#include "hphp/compiler/analysis/ast_walker.h"
#include "hphp/compiler/statement/statement.h"
using namespace HPHP;
@@ -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);
}
+8 -8
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,11 +14,11 @@
+----------------------------------------------------------------------+
*/
#ifndef __AST_WALKER_H__
#define __AST_WALKER_H__
#ifndef incl_HPHP_AST_WALKER_H_
#define incl_HPHP_AST_WALKER_H_
#include <compiler/hphp.h>
#include <compiler/construct.h>
#include "hphp/compiler/hphp.h"
#include "hphp/compiler/construct.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -26,7 +26,7 @@ namespace HPHP {
class AstWalkerState {
public:
AstWalkerState() : index(0) {}
AstWalkerState(ConstructRawPtr c) : cp(c), index(0) {}
explicit AstWalkerState(ConstructRawPtr c) : cp(c), index(0) {}
friend bool operator==(const AstWalkerState &s1,
const AstWalkerState &s2) {
@@ -40,7 +40,7 @@ public:
class AstWalkerStateVec : public std::vector<AstWalkerState> {
public:
AstWalkerStateVec() {}
AstWalkerStateVec(ConstructRawPtr cp) {
explicit AstWalkerStateVec(ConstructRawPtr cp) {
push_back(AstWalkerState(cp));
}
};
@@ -132,4 +132,4 @@ public:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __AST_WALKER_H__
#endif // incl_HPHP_AST_WALKER_H_
+3 -3
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -15,8 +15,8 @@
*/
#include <stdlib.h>
#include <compiler/analysis/bit_set_vec.h>
#include <compiler/analysis/data_flow.h>
#include "hphp/compiler/analysis/bit_set_vec.h"
#include "hphp/compiler/analysis/data_flow.h"
using namespace HPHP;
+2 -2
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -19,7 +19,7 @@
#include <limits.h>
#include <stddef.h>
#include "util/assertions.h"
#include "hphp/util/assertions.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
+32 -17
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,16 +14,17 @@
+----------------------------------------------------------------------+
*/
#include <compiler/expression/expression.h>
#include <compiler/analysis/block_scope.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/statement/statement_list.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/file_scope.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"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
using namespace HPHP;
@@ -89,13 +90,29 @@ AnalysisResultRawPtr BlockScope::getContainingProgram() {
return AnalysisResultRawPtr((AnalysisResult*)bs);
}
ClassScopeRawPtr BlockScope::getContainingClass() {
FunctionScopeRawPtr BlockScope::getContainingNonClosureFunction() {
BlockScope *bs = this;
if (bs->is(BlockScope::FunctionScope)) {
// walk out through all the closures
while (bs && bs->is(BlockScope::FunctionScope)) {
HPHP::FunctionScope *fs = static_cast<HPHP::FunctionScope*>(bs);
if (!fs->isClosure()) {
return FunctionScopeRawPtr(fs);
}
bs = bs->m_outerScope.get();
}
if (bs && !bs->is(BlockScope::ClassScope)) {
bs = 0;
return FunctionScopeRawPtr();
}
ClassScopeRawPtr BlockScope::getContainingClass() {
BlockScope *bs = getContainingNonClosureFunction().get();
if (!bs) {
bs = this;
}
if (bs && bs->is(BlockScope::FunctionScope)) {
bs = bs->m_outerScope.get();
}
if (!bs || !bs->is(BlockScope::ClassScope)) {
return ClassScopeRawPtr();
}
return ClassScopeRawPtr((HPHP::ClassScope*)bs);
}
@@ -138,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;
+10 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,14 +14,14 @@
+----------------------------------------------------------------------+
*/
#ifndef __BLOCK_SCOPE_H__
#define __BLOCK_SCOPE_H__
#ifndef incl_HPHP_BLOCK_SCOPE_H_
#define incl_HPHP_BLOCK_SCOPE_H_
#include <compiler/hphp.h>
#include "hphp/compiler/hphp.h"
#include <util/bits.h>
#include <util/lock.h>
#include <runtime/base/macros.h>
#include "hphp/util/bits.h"
#include "hphp/util/lock.h"
#include "hphp/runtime/base/macros.h"
#include <tbb/concurrent_hash_map.h>
@@ -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,
@@ -178,6 +178,7 @@ public:
VariableTablePtr getVariables() { return m_variables;}
ConstantTablePtr getConstants() { return m_constants;}
ClassScopeRawPtr getContainingClass();
FunctionScopeRawPtr getContainingNonClosureFunction();
FunctionScopeRawPtr getContainingFunction() const {
return FunctionScopeRawPtr(is(FunctionScope) ?
(HPHP::FunctionScope*)this : 0);
@@ -365,4 +366,4 @@ public:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __BLOCK_SCOPE_H__
#endif // incl_HPHP_BLOCK_SCOPE_H_
+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_
+202 -191
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,35 +14,39 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/construct.h"
#include "hphp/compiler/expression/class_constant_expression.h"
#include "hphp/compiler/expression/closure_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/statement/interface_statement.h"
#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/compiler/statement/class_variable.h"
#include "hphp/compiler/statement/class_constant.h"
#include "hphp/compiler/statement/use_trait_statement.h"
#include "hphp/compiler/statement/trait_require_statement.h"
#include "hphp/compiler/statement/trait_prec_statement.h"
#include "hphp/compiler/statement/trait_alias_statement.h"
#include "hphp/runtime/base/zend-string.h"
#include "hphp/util/util.h"
#include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/construct.h>
#include <compiler/expression/class_constant_expression.h>
#include <compiler/expression/constant_expression.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/expression/unary_op_expression.h>
#include <compiler/expression/simple_function_call.h>
#include <compiler/option.h>
#include <compiler/parser/parser.h>
#include <compiler/statement/interface_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/statement_list.h>
#include <runtime/base/builtin_functions.h>
#include <runtime/base/class_info.h>
#include <compiler/statement/class_variable.h>
#include <compiler/statement/class_constant.h>
#include <compiler/statement/use_trait_statement.h>
#include <compiler/statement/trait_prec_statement.h>
#include <compiler/statement/trait_alias_statement.h>
#include <runtime/base/zend/zend_string.h>
#include <util/util.h>
using namespace HPHP;
using std::map;
@@ -59,8 +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_needsEnableDestructor(0) {
m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) {
m_dynamic = Option::IsDynamicClass(m_name);
@@ -90,8 +93,8 @@ 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_needsInit(true), m_knownBases(0), m_needsEnableDestructor(0) {
m_derivedByDynamic(false), m_needsCppCtor(false),
m_needsInit(true), m_knownBases(0) {
BOOST_FOREACH(FunctionScopePtr f, methods) {
if (f->getName() == "__construct") setAttribute(HasConstructor);
else if (f->getName() == "__destruct") setAttribute(HasDestructor);
@@ -354,7 +357,7 @@ void ClassScope::collectMethods(AnalysisResultPtr ar,
setVolatile();
}
}
} else if (!Option::SystemGen) {
} else {
Compiler::Error(Compiler::UnknownBaseClass, m_stmt, base);
if (base == m_parent) {
ar->declareUnknownClass(m_parent);
@@ -401,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);
@@ -432,31 +424,67 @@ 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);
cloneMeth->addTraitMethodToScope(ar,
dynamic_pointer_cast<ClassScope>(shared_from_this()));
// Preserve original filename (as this varies per-function and not per-unit
// in the case of methods imported from flattened traits)
cloneMeth->setOriginalFilename(meth->getFileScope()->getName());
return cloneMeth;
}
void ClassScope::informClosuresAboutScopeClone(
ConstructPtr root,
FunctionScopePtr outerScope,
AnalysisResultPtr ar) {
if (!root) {
return;
}
for (int i = 0; i < root->getKidCount(); i++) {
ConstructPtr cons = root->getNthKid(i);
ClosureExpressionPtr closure =
dynamic_pointer_cast<ClosureExpression>(cons);
if (!closure) {
informClosuresAboutScopeClone(cons, outerScope, ar);
continue;
}
FunctionStatementPtr func = closure->getClosureFunction();
HPHP::FunctionScopePtr funcScope = func->getFunctionScope();
assert(funcScope->isClosure());
funcScope->addClonedTraitOuterScope(outerScope);
// Don't need to recurse
}
}
void ClassScope::addImportTraitMethod(const TraitMethod &traitMethod,
const string &methName) {
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,
@@ -517,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();
@@ -533,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;
@@ -564,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()
);
}
}
@@ -580,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++) {
@@ -597,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();
@@ -607,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());
@@ -619,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
@@ -631,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) {
@@ -647,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();
@@ -679,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++) {
@@ -715,88 +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 = 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[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) {
@@ -813,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
@@ -844,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
@@ -860,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 :
@@ -871,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;
@@ -892,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);
@@ -1162,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 {
@@ -1201,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);
}
@@ -1296,7 +1337,7 @@ void ClassScope::serialize(JSON::DocTarget::OutputStream &out) const {
ms.add("parent");
if (m_parent.empty()) {
out << JSON::Null;
out << JSON::Null();
} else {
out << GetDocName(out.analysisResult(), self, m_parent);
}
@@ -1400,36 +1441,6 @@ bool ClassScope::addFunction(AnalysisResultConstPtr ar,
return true;
}
/*
* A class without a constructor, but with a destructor may need a special
* create method to clear the NoDestructor flag - but only if
* there is a constructor somewhere above us, and if /that/ constructor
* doesnt need to clear the NoDestructor flag.
*/
bool ClassScope::needsEnableDestructor(
AnalysisResultConstPtr ar) const {
if (m_needsEnableDestructor & 2) {
return m_needsEnableDestructor & 1;
}
bool ret =
(!derivesFromRedeclaring() &&
!getAttribute(HasConstructor) &&
!getAttribute(ClassNameConstructor));
if (ret) {
if (!getAttribute(HasDestructor) && !m_parent.empty()) {
if (ClassScopePtr parent = getParentScope(ar)) {
if (!parent->needsEnableDestructor(ar)) {
ret = false;
}
}
}
}
m_needsEnableDestructor = ret ? 3 : 2;
return ret;
}
bool ClassScope::canSkipCreateMethod(AnalysisResultConstPtr ar) const {
// create() is not necessary if
// 1) not inheriting from any class
+49 -33
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,19 +14,20 @@
+----------------------------------------------------------------------+
*/
#ifndef __CLASS_SCOPE_H__
#define __CLASS_SCOPE_H__
#ifndef incl_HPHP_CLASS_SCOPE_H_
#define incl_HPHP_CLASS_SCOPE_H_
#include <compiler/analysis/block_scope.h>
#include <compiler/analysis/function_container.h>
#include <compiler/statement/class_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/trait_prec_statement.h>
#include <compiler/statement/trait_alias_statement.h>
#include <compiler/expression/user_attribute.h>
#include <util/json.h>
#include <util/case_insensitive.h>
#include <compiler/option.h>
#include "hphp/compiler/analysis/block_scope.h"
#include "hphp/compiler/analysis/function_container.h"
#include "hphp/compiler/statement/class_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#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/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);
/**
@@ -370,10 +380,19 @@ public:
return m_needsInit;
}
bool needsEnableDestructor(AnalysisResultConstPtr ar) const;
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;
@@ -383,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;
@@ -408,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;
@@ -425,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,10 +452,15 @@ private:
// for classes with more than 31 bases, bit 31 is set iff
// bases 32 through n are all known.
unsigned m_knownBases;
mutable unsigned m_needsEnableDestructor:2;
// 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,
FunctionScopePtr outerScope,
AnalysisResultPtr ar);
void setImportTraitMethodModifiers(const std::string &methName,
ClassScopePtr traitCls,
@@ -445,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,
@@ -476,14 +498,8 @@ private:
bool hasMethod(const std::string &methodName) const;
const std::string& getNewGeneratorName(FunctionScopePtr genFuncScope,
GeneratorRenameMap& genRenameMap);
void renameCreateContinuationCalls(AnalysisResultPtr ar, ConstructPtr c,
ImportedMethodMap &importedMethods);
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // __CLASS_SCOPE_H__
#endif // incl_HPHP_CLASS_SCOPE_H_
+9 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,13 +14,13 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/parser/parser.h>
#include <compiler/construct.h>
#include <compiler/option.h>
#include <util/exception.h>
#include <util/lock.h>
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/construct.h"
#include "hphp/compiler/option.h"
#include "hphp/util/exception.h"
#include "hphp/util/lock.h"
using namespace HPHP::JSON;
@@ -79,7 +79,7 @@ std::vector<const char *> &CodeErrors::getErrorTexts() {
if (ErrorTexts.empty()) {
ErrorTexts.resize(ErrorCount);
#define CODE_ERROR_ENTRY(x) ErrorTexts[x] = #x;
#include "compiler/analysis/core_code_error.inc"
#include "hphp/compiler/analysis/core_code_error.inc"
#undef CODE_ERROR_ENTRY
}
return ErrorTexts;
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,11 +14,11 @@
+----------------------------------------------------------------------+
*/
#ifndef __COMPILER_ERROR_H__
#define __COMPILER_ERROR_H__
#ifndef incl_HPHP_COMPILER_ERROR_H_
#define incl_HPHP_COMPILER_ERROR_H_
#include <compiler/analysis/type.h>
#include <util/json.h>
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/json.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -31,7 +31,7 @@ namespace Compiler {
enum ErrorType {
#define CODE_ERROR_ENTRY(x) x,
#include "compiler/analysis/core_code_error.inc"
#include "hphp/compiler/analysis/core_code_error.inc"
#undef CODE_ERROR_ENTRY
ErrorCount,
NoError
@@ -79,4 +79,4 @@ bool HasError(); // any error
///////////////////////////////////////////////////////////////////////////////
}}
#endif // __COMPILER_ERROR_H__
#endif // incl_HPHP_COMPILER_ERROR_H_
+13 -13
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,18 +14,18 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/type.h>
#include <compiler/code_generator.h>
#include <compiler/expression/expression.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/option.h>
#include <util/util.h>
#include <util/hash.h>
#include <compiler/analysis/class_scope.h>
#include <runtime/base/complex_types.h>
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/option.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/runtime/base/complex-types.h"
using namespace HPHP;
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,11 +14,11 @@
+----------------------------------------------------------------------+
*/
#ifndef __CONSTANT_TABLE_H__
#define __CONSTANT_TABLE_H__
#ifndef incl_HPHP_CONSTANT_TABLE_H_
#define incl_HPHP_CONSTANT_TABLE_H_
#include <compiler/analysis/symbol_table.h>
#include <compiler/analysis/block_scope.h>
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/analysis/block_scope.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -37,7 +37,7 @@ DECLARE_BOOST_TYPES(ClassScope);
*/
class ConstantTable : public SymbolTable {
public:
ConstantTable(BlockScope &blockScope);
explicit ConstantTable(BlockScope &blockScope);
/**
* Whether defining something to be non-scalar value or redeclared, or
@@ -103,4 +103,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __CONSTANT_TABLE_H__
#endif // incl_HPHP_CONSTANT_TABLE_H_
+108 -92
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -13,32 +13,32 @@
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "compiler/analysis/ast_walker.h"
#include "compiler/analysis/control_flow.h"
#include "compiler/analysis/data_flow.h"
#include "compiler/expression/expression.h"
#include "compiler/expression/binary_op_expression.h"
#include "compiler/expression/unary_op_expression.h"
#include "compiler/expression/qop_expression.h"
#include "compiler/statement/statement.h"
#include "compiler/statement/method_statement.h"
#include "compiler/statement/statement_list.h"
#include "compiler/statement/if_branch_statement.h"
#include "compiler/statement/for_statement.h"
#include "compiler/statement/while_statement.h"
#include "compiler/statement/do_statement.h"
#include "compiler/statement/foreach_statement.h"
#include "compiler/statement/switch_statement.h"
#include "compiler/statement/break_statement.h"
#include "compiler/statement/try_statement.h"
#include "compiler/statement/finally_statement.h"
#include "compiler/statement/label_statement.h"
#include "compiler/statement/goto_statement.h"
#include "compiler/statement/case_statement.h"
#include "hphp/compiler/analysis/control_flow.h"
#include <boost/graph/depth_first_search.hpp>
#include "hphp/compiler/analysis/ast_walker.h"
#include "hphp/compiler/analysis/data_flow.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/expression/qop_expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/statement/if_branch_statement.h"
#include "hphp/compiler/statement/for_statement.h"
#include "hphp/compiler/statement/while_statement.h"
#include "hphp/compiler/statement/do_statement.h"
#include "hphp/compiler/statement/foreach_statement.h"
#include "hphp/compiler/statement/switch_statement.h"
#include "hphp/compiler/statement/break_statement.h"
#include "hphp/compiler/statement/try_statement.h"
#include "hphp/compiler/statement/finally_statement.h"
#include "hphp/compiler/statement/label_statement.h"
#include "hphp/compiler/statement/goto_statement.h"
#include "hphp/compiler/statement/case_statement.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -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;
@@ -182,7 +181,7 @@ public:
class dfs_dump : public boost::default_dfs_visitor {
public:
dfs_dump(AnalysisResultConstPtr ar) : m_ar(ar) {}
explicit dfs_dump(AnalysisResultConstPtr ar) : m_ar(ar) {}
void discover_vertex(ControlFlowGraph::vertex_descriptor u,
const ControlFlowGraph &g) {
@@ -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();
@@ -329,9 +329,10 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
}
case Statement::KindOfForStatement: {
ConstructRawPtr cond(s->getNthKid(ForStatement::CondExpr));
ConstructRawPtr body(s->getNthKid(ForStatement::BodyStmt));
ConstructRawPtr incr(s->getNthKid(ForStatement::IncExpr));
ForStatementPtr fs(static_pointer_cast<ForStatement>(s));
ConstructRawPtr body(fs->getBody());
ConstructRawPtr cond(fs->getCondExp());
ConstructRawPtr incr(fs->getIncExp());
if (cond) addEdge(cond, AfterConstruct, s, AfterConstruct);
ConstructRawPtr end = incr ? incr : body ? body : cond;
ConstructRawPtr start = cond ? cond : body ? body : incr;
@@ -341,8 +342,9 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
}
case Statement::KindOfWhileStatement: {
ConstructRawPtr cond(s->getNthKid(WhileStatement::CondExpr));
ConstructRawPtr body(s->getNthKid(WhileStatement::BodyStmt));
WhileStatementPtr ws(static_pointer_cast<WhileStatement>(s));
ConstructRawPtr body(ws->getBody());
ConstructRawPtr cond(ws->getCondExp());
addEdge(cond, AfterConstruct, s, AfterConstruct);
addEdge(body ? body : cond, AfterConstruct, cond, BeforeConstruct);
noFallThrough(s);
@@ -350,15 +352,16 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
}
case Statement::KindOfDoStatement: {
ConstructRawPtr cond(s->getNthKid(DoStatement::CondExpr));
addEdge(cond, AfterConstruct, s, BeforeConstruct);
DoStatementPtr ds(static_pointer_cast<DoStatement>(s));
addEdge(ds->getCondExp(), AfterConstruct, s, BeforeConstruct);
break;
}
case Statement::KindOfForEachStatement: {
ConstructRawPtr body(s->getNthKid(ForEachStatement::BodyStmt));
ConstructRawPtr name(s->getNthKid(ForEachStatement::NameExpr));
ConstructRawPtr value(s->getNthKid(ForEachStatement::ValueExpr));
ForEachStatementPtr fs(static_pointer_cast<ForEachStatement>(s));
ConstructRawPtr body(fs->getBody());
ConstructRawPtr name(fs->getNameExp());
ConstructRawPtr value(fs->getValueExp());
ConstructRawPtr begin = name ? name : value;
ConstructRawPtr end = body ? body : value;
addEdge(end, AfterConstruct, begin, BeforeConstruct);
@@ -414,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
@@ -450,23 +453,31 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
} else {
ConstructRawPtr kid;
switch (l->getKindOf()) {
case Statement::KindOfForEachStatement:
kid = l->getNthKid(ForEachStatement::NameExpr);
case Statement::KindOfForEachStatement: {
ForEachStatementPtr fs(static_pointer_cast<ForEachStatement>(l));
kid = fs->getNameExp();
if (!kid) {
kid = l->getNthKid(ForEachStatement::ValueExpr);
kid = fs->getValueExp();
}
break;
case Statement::KindOfForStatement:
kid = l->getNthKid(ForStatement::IncExpr);
if (!kid) kid = l->getNthKid(ForStatement::CondExpr);
if (!kid) kid = l->getNthKid(ForStatement::BodyStmt);
}
case Statement::KindOfForStatement: {
ForStatementPtr fs(static_pointer_cast<ForStatement>(l));
kid = fs->getIncExp();
if (!kid) kid = fs->getCondExp();
if (!kid) kid = fs->getBody();
break;
case Statement::KindOfWhileStatement:
kid = l->getNthKid(WhileStatement::CondExpr);
}
case Statement::KindOfWhileStatement: {
WhileStatementPtr ws(static_pointer_cast<WhileStatement>(l));
kid = ws->getCondExp();
break;
case Statement::KindOfDoStatement:
kid = l->getNthKid(DoStatement::CondExpr);
}
case Statement::KindOfDoStatement: {
DoStatementPtr ds(static_pointer_cast<DoStatement>(l));
kid = ds->getCondExp();
break;
}
default:
always_assert(0);
}
@@ -487,6 +498,7 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
}
case Statement::KindOfEchoStatement:
case Statement::KindOfTypedefStatement:
break;
default:
@@ -495,36 +507,36 @@ int ControlFlowBuilder::before(ConstructRawPtr cp) {
} else {
ExpressionPtr e(dynamic_pointer_cast<Expression>(cp));
switch (e->getKindOf()) {
case Expression::KindOfBinaryOpExpression:
{
BinaryOpExpressionPtr b(
static_pointer_cast<BinaryOpExpression>(e));
if (b->isShortCircuitOperator()) {
ConstructPtr trueBranch, falseBranch;
ConstructLocation tLoc, fLoc;
getTrueFalseBranches(0, trueBranch, tLoc, falseBranch, fLoc);
assert(trueBranch);
assert(falseBranch);
if (b->isLogicalOrOperator()) {
addEdge(e->getNthExpr(0), AfterConstruct, trueBranch, tLoc);
} else {
addEdge(e->getNthExpr(0), AfterConstruct, falseBranch, fLoc);
}
case Expression::KindOfBinaryOpExpression: {
BinaryOpExpressionPtr b(static_pointer_cast<BinaryOpExpression>(e));
if (b->isShortCircuitOperator()) {
ConstructPtr trueBranch, falseBranch;
ConstructLocation tLoc, fLoc;
getTrueFalseBranches(0, trueBranch, tLoc, falseBranch, fLoc);
assert(trueBranch);
assert(falseBranch);
if (b->isLogicalOrOperator()) {
addEdge(b->getExp1(), AfterConstruct, trueBranch, tLoc);
} else {
addEdge(b->getExp1(), AfterConstruct, falseBranch, fLoc);
}
}
break;
case Expression::KindOfQOpExpression:
if (ExpressionPtr e1 = e->getNthExpr(1)) {
addEdge(e->getNthExpr(0), AfterConstruct,
e->getNthExpr(2), BeforeConstruct);
}
case Expression::KindOfQOpExpression: {
QOpExpressionPtr q(static_pointer_cast<QOpExpression>(e));
if (ExpressionPtr e1 = q->getYes()) {
addEdge(q->getCondition(), AfterConstruct,
q->getNo(), BeforeConstruct);
addEdge(e1, AfterConstruct,
e->getNthExpr(2), AfterConstruct);
q->getNo(), AfterConstruct);
noFallThrough(e1);
} else {
addEdge(e->getNthExpr(0), AfterConstruct,
e->getNthExpr(2), AfterConstruct);
addEdge(q->getCondition(), AfterConstruct,
q->getNo(), AfterConstruct);
}
break;
}
default:
break;
}
@@ -586,32 +598,36 @@ void ControlFlowBuilder::getTrueFalseBranches(
ConstructPtr c(top(level));
if (StatementPtr s = dynamic_pointer_cast<Statement>(c)) {
int kidBodyIdx = -1;
StatementPtr kidBody;
switch (s->getKindOf()) {
case Statement::KindOfForStatement:
case Statement::KindOfForStatement: {
// examine which context we're in
{
ConstructPtr kid(top(level - 1));
if (kid == s->getNthKid(ForStatement::InitExpr)) {
; // just do the default case
} else if (kid == s->getNthKid(ForStatement::CondExpr)) {
kidBodyIdx = ForStatement::BodyStmt;
goto loop_stmt;
} else if (kid == s->getNthKid(ForStatement::IncExpr)) {
; // just do the default case
} else {
assert(false);
}
ForStatementPtr fs(static_pointer_cast<ForStatement>(s));
ConstructPtr kid(top(level - 1));
if (kid == fs->getInitExp()) {
; // just do the default case
} else if (kid == fs->getCondExp()) {
kidBody = fs->getBody();
goto loop_stmt;
} else if (kid == fs->getIncExp()) {
; // just do the default case
} else {
assert(false);
}
break;
case Statement::KindOfWhileStatement:
kidBodyIdx = WhileStatement::BodyStmt;
}
case Statement::KindOfWhileStatement: {
WhileStatementPtr ws(static_pointer_cast<WhileStatement>(s));
kidBody = ws->getBody();
goto loop_stmt;
case Statement::KindOfDoStatement:
kidBodyIdx = DoStatement::BodyStmt;
}
case Statement::KindOfDoStatement: {
DoStatementPtr ds(static_pointer_cast<DoStatement>(s));
kidBody = ds->getBody();
}
loop_stmt:
if (!trueBranch) {
trueBranch = s->getNthKid(kidBodyIdx);
trueBranch = kidBody;
tLoc = BeforeConstruct;
}
if (!falseBranch) {
@@ -852,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(),
+13 -8
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,17 +14,17 @@
+----------------------------------------------------------------------+
*/
#ifndef __CONTROL_FLOW_H__
#define __CONTROL_FLOW_H__
#ifndef incl_HPHP_CONTROL_FLOW_H_
#define incl_HPHP_CONTROL_FLOW_H_
#include <boost/graph/properties.hpp>
#include <boost/graph/adjacency_iterator.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <compiler/hphp.h>
#include "hphp/compiler/hphp.h"
#include <compiler/analysis/ast_walker.h>
#include <compiler/analysis/bit_set_vec.h>
#include "hphp/compiler/analysis/ast_walker.h"
#include "hphp/compiler/analysis/bit_set_vec.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -65,6 +65,8 @@ struct graph_traits<HPHP::ControlFlowGraph> {
typedef int vertices_size_type;
typedef int edges_size_type;
typedef std::list<HPHP::ControlEdge*>::size_type degree_size_type;
static vertex_descriptor null_vertex() { return nullptr; }
};
template<>
@@ -309,7 +311,10 @@ inline void put(boost::vertex_color_t c,
class ControlFlowGraphWalker : public FunctionWalker {
public:
ControlFlowGraphWalker(ControlFlowGraph *g) : m_block(0), m_graph(*g) {}
explicit ControlFlowGraphWalker(ControlFlowGraph *g)
: m_block(0)
, m_graph(*g)
{}
template <class T>
void walk(T &t) {
std::pair<ControlFlowGraph::vertex_iterator,
@@ -333,4 +338,4 @@ protected:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __CONTROL_FLOW_H__
#endif // incl_HPHP_CONTROL_FLOW_H_
+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)
+16 -15
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,12 +14,12 @@
+----------------------------------------------------------------------+
*/
#include "compiler/analysis/data_flow.h"
#include "hphp/compiler/analysis/data_flow.h"
#include "compiler/expression/expression.h"
#include "compiler/expression/simple_variable.h"
#include "compiler/expression/binary_op_expression.h"
#include "compiler/expression/list_assignment.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/expression/list_assignment.h"
using namespace HPHP;
using std::pair;
@@ -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;
}
@@ -350,12 +350,13 @@ void DataFlowWalker::process(ExpressionPtr e, bool doAccessChains) {
case Expression::KindOfAssignmentExpression:
case Expression::KindOfBinaryOpExpression:
case Expression::KindOfUnaryOpExpression: {
ExpressionPtr var = e->getNthExpr(0);
ExpressionPtr var = e->getStoreVariable();
if (var && var->getContext() & (Expression::AssignmentLHS|
Expression::OprLValue)) {
processAccessChain(var);
processAccess(var);
}
// fall through
}
default:
processAccess(e);
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,11 +14,11 @@
+----------------------------------------------------------------------+
*/
#ifndef __DATA_FLOW_H__
#define __DATA_FLOW_H__
#ifndef incl_HPHP_DATA_FLOW_H_
#define incl_HPHP_DATA_FLOW_H_
#include <compiler/analysis/bit_set_vec.h>
#include <compiler/analysis/control_flow.h>
#include "hphp/compiler/analysis/bit_set_vec.h"
#include "hphp/compiler/analysis/control_flow.h"
namespace HPHP {
@@ -91,7 +91,7 @@ private:
class DataFlowWalker : public ControlFlowGraphWalker {
public:
DataFlowWalker(ControlFlowGraph *g) : ControlFlowGraphWalker(g) {}
explicit DataFlowWalker(ControlFlowGraph *g) : ControlFlowGraphWalker(g) {}
template<class T>
void walk(T &t) { ControlFlowGraphWalker::walk(t); }
@@ -107,4 +107,4 @@ public:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __DATA_FLOW_H__
#endif // incl_HPHP_DATA_FLOW_H_
+12 -12
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,15 +14,15 @@
+----------------------------------------------------------------------+
*/
#ifndef __DEPTH_FIRST_VISITOR_H__
#define __DEPTH_FIRST_VISITOR_H__
#ifndef incl_HPHP_DEPTH_FIRST_VISITOR_H_
#define incl_HPHP_DEPTH_FIRST_VISITOR_H_
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/ast_walker.h>
#include <compiler/analysis/block_scope.h>
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/ast_walker.h"
#include "hphp/compiler/analysis/block_scope.h"
#include <compiler/expression/expression.h>
#include <compiler/statement/statement.h>
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/statement/statement.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -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);
@@ -230,4 +230,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __DEPTH_FIRST_VISITOR_H__
#endif // incl_HPHP_DEPTH_FIRST_VISITOR_H_
+9 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,12 +14,12 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/dictionary.h>
#include <compiler/expression/expression.h>
#include <compiler/statement/statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/statement_list.h>
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/dictionary.h"
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
using namespace HPHP;
using std::vector;
@@ -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);
}
}
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,11 +14,11 @@
+----------------------------------------------------------------------+
*/
#ifndef __DICTIONARY_H__
#define __DICTIONARY_H__
#ifndef incl_HPHP_DICTIONARY_H_
#define incl_HPHP_DICTIONARY_H_
#include <compiler/hphp.h>
#include <compiler/analysis/data_flow.h>
#include "hphp/compiler/hphp.h"
#include "hphp/compiler/analysis/data_flow.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -32,7 +32,7 @@ class Dictionary {
public:
typedef std::vector<ExpressionPtr> IdMap;
Dictionary(AliasManager &am);
explicit Dictionary(AliasManager &am);
void build(MethodStatementPtr s);
void build(StatementPtr s);
void build(ExpressionPtr s);
@@ -78,4 +78,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __DICTIONARY_H__
#endif // incl_HPHP_DICTIONARY_H_
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+375 -119
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,18 +14,23 @@
+----------------------------------------------------------------------+
*/
#ifndef __COMPILER_EMITTER_H__
#define __COMPILER_EMITTER_H__
#ifndef incl_HPHP_COMPILER_EMITTER_H_
#define incl_HPHP_COMPILER_EMITTER_H_
#include <compiler/expression/expression.h>
#include <compiler/statement/statement.h>
#include <compiler/statement/use_trait_statement.h>
#include <compiler/statement/trait_prec_statement.h>
#include <compiler/statement/trait_alias_statement.h>
#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"
#include <runtime/vm/func.h>
#include <runtime/vm/unit.h>
#include <util/hash.h>
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/unit.h"
#include "hphp/util/hash.h"
#include <deque>
#include <utility>
namespace HPHP {
@@ -40,20 +45,12 @@ DECLARE_BOOST_TYPES(SimpleFunctionCall);
DECLARE_BOOST_TYPES(SwitchStatement);
DECLARE_BOOST_TYPES(ForEachStatement);
class StaticClassName;
class HhbcExtFuncInfo;
class HhbcExtClassInfo;
namespace Compiler {
///////////////////////////////////////////////////////////////////////////////
using VM::Offset;
using VM::Func;
using VM::Class;
using VM::Unit;
using VM::InvalidAbsoluteOffset;
using VM::Opcode;
using VM::Id;
using namespace VM;
// Forward declarations.
class Label;
class EmitterVisitor;
@@ -96,6 +93,13 @@ public:
Id str;
Label* dest;
};
struct IterPair {
IterPair(IterKind k, Id i) : kind(k), id(i) {}
IterKind kind;
Id id;
};
#define O(name, imm, pop, push, flags) \
void name(imm);
#define NA
@@ -107,18 +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
@@ -129,8 +135,9 @@ public:
#undef MA
#undef BLA
#undef SLA
#undef ILA
#undef IVA
#undef HA
#undef LA
#undef IA
#undef I64A
#undef DA
@@ -138,6 +145,7 @@ public:
#undef AA
#undef BA
#undef OA
#undef VSA
private:
ConstructPtr m_node;
UnitEmitter& m_ue;
@@ -284,7 +292,7 @@ public:
class Label {
public:
Label() : m_off(InvalidAbsoluteOffset) {}
Label(Emitter& e) : m_off(InvalidAbsoluteOffset) {
explicit Label(Emitter& e) : m_off(InvalidAbsoluteOffset) {
set(e);
}
Offset getAbsoluteOffset() const { return m_off; }
@@ -315,15 +323,138 @@ 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:
EmitterVisitor(UnitEmitter& ue);
typedef std::vector<int> IndexChain;
typedef Emitter::IterPair IterPair;
typedef std::vector<IterPair> IterVec;
explicit EmitterVisitor(UnitEmitter& ue);
~EmitterVisitor();
bool visit(ConstructPtr c);
@@ -331,9 +462,10 @@ public:
void visitKids(ConstructPtr c);
void visit(FileScopePtr file);
void assignLocalVariableIds(FunctionScopePtr fs);
void assignFinallyVariableIds();
void fixReturnType(Emitter& e, FunctionCallPtr fn,
bool isBuiltinCall = false);
typedef std::vector<int> IndexChain;
Func* builtinFunc = nullptr);
void visitListAssignmentLHS(Emitter& e, ExpressionPtr exp,
IndexChain& indexChain,
std::vector<IndexChain*>& chainList);
@@ -347,9 +479,10 @@ public:
}
bool evalStackIsUnknown() { return m_evalStackIsUnknown; }
void popEvalStack(char symFlavor, int arg = -1, int pos = -1);
void popSymbolicLocal(Opcode opcode, int arg = -1, int pos = -1);
void popEvalStackLMany();
void popSymbolicLocal(Op opcode, int arg = -1, int pos = -1);
void popEvalStackMMany();
void popEvalStackMany(int len, char symFlavor);
void popEvalStackCVMany(int len);
void pushEvalStack(char symFlavor);
void peekEvalStack(char symFlavor, int depthActual);
void pokeEvalStack(char symFlavor, int depthActual);
@@ -359,40 +492,51 @@ public:
recordJumpTarget(target, m_evalStack);
}
void restoreJumpTargetEvalStack();
void recordCall();
bool isJumpTarget(Offset target);
void setPrevOpcode(Opcode op) { m_prevOpcode = op; }
Opcode getPrevOpcode() const { return m_prevOpcode; }
void setPrevOpcode(Op op) { m_prevOpcode = op; }
Op getPrevOpcode() const { return m_prevOpcode; }
bool currentPositionIsReachable() {
return (m_ue.bcPos() == m_curFunc->base()
|| 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; }
};
enum IterKind {
KindOfIter = 0,
KindOfMIter = 1
};
void pushIterScope(Id id, bool itRef = false) {
IterKind itKind = itRef ? KindOfMIter : KindOfIter;
m_pendingIters.push_back(std::pair<Id,IterKind>(id,itKind));
void pushIterScope(Id id, IterKind kind) {
m_pendingIters.emplace_back(id, kind);
}
void popIterScope() { m_pendingIters.pop_back(); }
private:
typedef std::pair<StringData*, bool> ClosureUseVar; // (name, byRef)
typedef std::vector<ClosureUseVar> ClosureUseVarVec;
typedef std::vector<std::pair<Id,IterKind> > PendingIterVec;
typedef std::pair<StringData*, ExpressionPtr> NonScalarPair;
typedef std::vector<NonScalarPair> NonScalarVec;
typedef std::pair<Id, int> StrCase;
class PostponedMeth {
public:
PostponedMeth(MethodStatementPtr m, FuncEmitter* fe, bool top,
@@ -403,6 +547,7 @@ private:
bool m_top;
ClosureUseVarVec* m_closureUseVars;
};
class PostponedCtor {
public:
PostponedCtor(InterfaceStatementPtr is, FuncEmitter* fe)
@@ -410,8 +555,7 @@ private:
InterfaceStatementPtr m_is;
FuncEmitter* m_fe;
};
typedef std::pair<StringData*, ExpressionPtr> NonScalarPair;
typedef std::vector<NonScalarPair> NonScalarVec;
class PostponedNonScalars {
public:
PostponedNonScalars(InterfaceStatementPtr is, FuncEmitter* fe,
@@ -424,6 +568,7 @@ private:
FuncEmitter* m_fe;
NonScalarVec* m_vec;
};
class PostponedClosureCtor {
public:
PostponedClosureCtor(ClosureUseVarVec& v, ClosureExpressionPtr e,
@@ -433,37 +578,12 @@ private:
ClosureExpressionPtr m_expr;
FuncEmitter* m_fe;
};
class ControlTargets {
class CatchRegion {
public:
ControlTargets(Id itId, bool itRef, Label& brkTarg, Label& cntTarg,
Label& brkHand, Label& cntHand) :
m_itId(itId), m_itRef(itRef), m_brkTarg(brkTarg), m_cntTarg(cntTarg),
m_brkHand(brkHand), m_cntHand(cntHand) {}
Id m_itId;
bool m_itRef;
Label& m_brkTarg; // Jump here for "break;" (after doing IterFree)
Label& m_cntTarg; // Jump here for "continue;"
Label& m_brkHand; // Push N and jump here for "break N;"
Label& m_cntHand; // Push N and jump here for "continue N;"
};
class ControlTargetPusher {
public:
ControlTargetPusher(EmitterVisitor* e, Id itId, bool itRef, Label& brkTarg,
Label& cntTarg, Label& brkHand, Label& cntHand) : m_e(e) {
e->m_contTargets.push_front(ControlTargets(itId, itRef, brkTarg, cntTarg,
brkHand, cntHand));
}
~ControlTargetPusher() {
m_e->m_contTargets.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;
@@ -474,15 +594,27 @@ private:
std::set<StringData*, string_data_lt> m_names;
std::vector<std::pair<StringData*, Label*> > m_catchLabels;
};
class FaultRegion {
public:
FaultRegion(Offset start, Offset end, Id iterId)
: m_start(start), m_end(end), m_iterId(iterId) {}
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) {}
Offset m_start;
Offset m_end;
Label* m_func;
Id m_iterId;
Label m_func;
IterKind m_iterKind;
};
class FPIRegion {
public:
FPIRegion(Offset start, Offset end, Offset fpOff)
@@ -491,7 +623,7 @@ private:
Offset m_end;
Offset m_fpOff;
};
typedef std::pair<Id, int> StrCase;
struct SwitchState : private boost::noncopyable {
SwitchState() : nonZeroI(-1), defI(-1) {}
std::map<int64_t, int> cases; // a map from int (or litstr id) to case index
@@ -502,12 +634,13 @@ private:
int defI;
};
private:
static const size_t kMinStringSwitchCases = 8;
UnitEmitter& m_ue;
FuncEmitter* m_curFunc;
FileScopePtr m_file;
Opcode m_prevOpcode;
Op m_prevOpcode;
std::deque<PostponedMeth> m_postponedMeths;
std::deque<PostponedCtor> m_postponedCtors;
@@ -516,33 +649,44 @@ private:
std::deque<PostponedNonScalars> m_postponedCinits;
std::deque<PostponedClosureCtor> m_postponedClosureCtors;
PendingIterVec m_pendingIters;
typedef std::map<const StringData*, Label*, string_data_lt> LabelMap;
LabelMap m_methLabels;
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;
hphp_hash_map<Offset, SymbolicStack> m_jumpTargetEvalStacks;
int m_actualStackHighWater;
int m_fdescHighWater;
int m_closureCounter; // used to uniquify closures' mangled names
std::deque<ControlTargets> m_contTargets;
std::deque<Funclet> m_funclets;
std::deque<ExnHandlerRegion*> m_exnHandlers;
typedef tbb::concurrent_hash_map<const StringData*, int,
StringDataHashCompare> EmittedClosures;
static EmittedClosures s_emittedClosures;
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;
MetaInfoBuilder m_metaInfo;
public:
Label& topBreakHandler() { return m_contTargets.front().m_brkHand; }
Label& topContHandler() { return m_contTargets.front().m_cntHand; }
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 {
@@ -554,25 +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);
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);
@@ -582,8 +721,10 @@ public:
template<class Expr> void emitVirtualClassBase(Emitter&, Expr* node);
void emitResolveClsBase(Emitter& e, int pos);
void emitClsIfSPropBase(Emitter& e);
Label* getContinuationGotoLabel(StatementPtr s);
void emitContinuationSwitch(Emitter& e, SwitchStatementPtr s);
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);
void emitIntegerSwitch(Emitter& e, SwitchStatementPtr s,
std::vector<Label>& caseLabels, Label& done,
@@ -610,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();
@@ -629,31 +796,94 @@ public:
};
bool emitCallUserFunc(Emitter& e, SimpleFunctionCallPtr node);
bool canEmitBuiltinCall(FunctionCallPtr fn, const std::string& name,
int numParams);
void emitFuncCall(Emitter& e, FunctionCallPtr node);
Func* canEmitBuiltinCall(const std::string& name, int numParams);
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 emitBreakHandler(Emitter& e, Label& brkTarg, Label& cntTarg,
Label& brkHand, Label& cntHand, Id iter = -1,
IterKind itKind = KindOfIter);
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);
void newFaultRegion(Offset start, Offset end, Thunklet* t, Id iter = -1);
struct FaultIterInfo {
Id iterId;
IterKind kind;
};
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);
StringData* newClosureName();
void initScalar(TypedValue& tvVal, ExpressionPtr val);
bool requiresDeepInit(ExpressionPtr initExpr) const;
@@ -662,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,
@@ -679,4 +935,4 @@ extern "C" {
}
}
#endif // __COMPILER_EMITTER_H__
#endif // incl_HPHP_COMPILER_EMITTER_H_
+9 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,14 +14,14 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/expr_dict.h>
#include "hphp/compiler/analysis/expr_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include <compiler/expression/expression.h>
#include <compiler/expression/assignment_expression.h>
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include <compiler/statement/statement.h>
#include <compiler/statement/method_statement.h>
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/method_statement.h"
using namespace HPHP;
using std::vector;
@@ -59,7 +59,7 @@ void ExprDict::getTypes(ExpressionPtr e, TypePtrIdxPairVec &types) {
class TypeFunc { public:
bool operator()(const TypePtrIdxPair& entry) const {
return entry.first;
return entry.first != nullptr;
}
};
static TypeFunc s_type_func;
@@ -313,7 +313,7 @@ void ExprDict::updateAccess(ExpressionPtr e) {
BitOps::set_bit(aid, m_altered, true);
}
if (!(cls & Expression::Store) ||
a != e->getNthExpr(0)) {
a != e->getStoreVariable()) {
a->clearAvailable();
m_avlAccess[i] = m_avlAccess[--n];
m_avlAccess.resize(n);
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,10 +14,10 @@
+----------------------------------------------------------------------+
*/
#ifndef __EXPR_DICT_H__
#define __EXPR_DICT_H__
#ifndef incl_HPHP_EXPR_DICT_H_
#define incl_HPHP_EXPR_DICT_H_
#include <compiler/analysis/dictionary.h>
#include "hphp/compiler/analysis/dictionary.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -27,7 +27,7 @@ typedef std::vector<TypePtrIdxPair> TypePtrIdxPairVec;
class ExprDict : public Dictionary {
public:
ExprDict(AliasManager &am);
explicit ExprDict(AliasManager &am);
/* Building the dictionary */
void build(MethodStatementPtr m);
void visit(ExpressionPtr e);
@@ -43,8 +43,8 @@ public:
TypePtr propagateType(ExpressionPtr e);
void getTypes(ExpressionPtr e, TypePtrIdxPairVec &types);
private:
private:
/**
* types is filled with (type assertion, canon id for that type assertion)
* tuples
@@ -94,4 +94,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __EXPR_DICT_H__
#endif // incl_HPHP_EXPR_DICT_H_
+144 -124
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -13,38 +13,40 @@
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/analysis/file_scope.h"
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/statement/statement_list.h>
#include <compiler/statement/exp_statement.h>
#include <compiler/option.h>
#include <compiler/analysis/constant_table.h>
#include <compiler/analysis/function_scope.h>
#include <sys/stat.h>
#include <compiler/parser/parser.h>
#include <util/logger.h>
#include <util/util.h>
#include <util/base.h>
#include <compiler/expression/expression_list.h>
#include <compiler/statement/function_statement.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/expression/simple_function_call.h>
#include <compiler/expression/include_expression.h>
#include <compiler/expression/user_attribute.h>
#include <runtime/base/complex_types.h>
#include "folly/ScopeGuard.h"
using namespace HPHP;
#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"
#include "hphp/compiler/statement/exp_statement.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/constant_table.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/logger.h"
#include "hphp/util/util.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"
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,25 +96,49 @@ 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;
ExpressionListPtr args(new ExpressionList(scope, loc));
args->addElement(Expression::MakeScalarExpression(ar, scope, loc, msg));
SimpleFunctionCallPtr e(
new SimpleFunctionCall(scope, loc, "throw_fatal", args, ExpressionPtr()));
e->setThrowFatal();
ExpStatementPtr exp(new ExpStatement(scope, loc, e));
StatementListPtr stmts(new StatementList(scope, loc));
new SimpleFunctionCall(scope, loc, "throw_fatal", false, args,
ExpressionPtr()));
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,
@@ -192,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 {
@@ -239,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) {
@@ -306,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);
}
@@ -394,11 +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,
@@ -430,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());
}
@@ -455,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);
}
}
@@ -491,3 +510,4 @@ void FileScope::serialize(JSON::DocTarget::OutputStream &out) const {
ms.done();
}
}
+57 -30
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,16 +14,20 @@
+----------------------------------------------------------------------+
*/
#ifndef __FILE_SCOPE_H__
#define __FILE_SCOPE_H__
#ifndef incl_HPHP_FILE_SCOPE_H_
#define incl_HPHP_FILE_SCOPE_H_
#include <compiler/analysis/block_scope.h>
#include <compiler/analysis/function_container.h>
#include <compiler/analysis/code_error.h>
#include <compiler/code_generator.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 <util/json.h>
#include <runtime/base/md5.h>
#include "hphp/compiler/json.h"
#include "hphp/util/md5.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -59,7 +63,8 @@ public:
MixedVariableArgument = 0x800, // variable args, may or may not be ref'd
IsFoldable = 0x1000,// function can be constant folded
NeedsActRec = 0x2000,// builtin function needs ActRec
IgnoreRedefinition = 0x4000,// ignore redefinition of builtin function
AllowOverride = 0x4000,// allow override of systemlib or builtin
NeedsFinallyLocals = 0x8000,
};
typedef boost::adjacency_list<boost::setS, boost::vecS> Graph;
@@ -75,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;
@@ -105,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);
@@ -135,6 +144,27 @@ public:
void addConstantDependency(AnalysisResultPtr ar,
const std::string &decname);
void addClassAlias(const std::string& target, const std::string& 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 {
return m_classAliasMap;
}
void addTypeAliasName(const std::string& name) {
m_typeAliasNames.insert(boost::to_lower_copy(name));
}
std::set<std::string> const& getTypeAliasNames() const {
return m_typeAliasNames;
}
/**
* Called only by World
*/
@@ -143,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);
@@ -162,31 +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;
@@ -198,14 +217,22 @@ private:
vertex_descriptor m_vertex;
std::string m_pseudoMainName;
std::set<std::string> m_pseudoMainVariables;
BlockScopeSet m_providedDefs;
std::set<std::string> m_redecBases;
// Map from class alias names to the class they are aliased to.
// This is only needed in WholeProgram mode.
std::multimap<std::string,std::string> m_classAliasMap;
// Set of names that are on the left hand side of type alias
// declarations. We need this to make sure we don't mark classes
// with the same name Unique.
std::set<std::string> m_typeAliasNames;
FunctionScopePtr createPseudoMain(AnalysisResultConstPtr ar);
void setFileLevel(StatementListPtr stmt);
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // __FILE_SCOPE_H__
#endif // incl_HPHP_FILE_SCOPE_H_
+11 -11
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,16 +14,16 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/function_container.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/statement/statement_list.h>
#include <compiler/option.h>
#include <util/util.h>
#include <util/hash.h>
#include "hphp/compiler/analysis/function_container.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/option.h"
#include "hphp/util/util.h"
#include "hphp/util/hash.h"
using namespace HPHP;
+6 -6
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,17 +14,17 @@
+----------------------------------------------------------------------+
*/
#ifndef __FUNCTION_CONTAINER_H__
#define __FUNCTION_CONTAINER_H__
#ifndef incl_HPHP_FUNCTION_CONTAINER_H_
#define incl_HPHP_FUNCTION_CONTAINER_H_
#include <compiler/hphp.h>
#include "hphp/compiler/hphp.h"
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);
@@ -56,4 +56,4 @@ protected:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __FUNCTION_CONTAINER_H__
#endif // incl_HPHP_FUNCTION_CONTAINER_H_
+150 -122
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,31 +14,31 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/expression/constant_expression.h>
#include <compiler/expression/modifier_expression.h>
#include <compiler/expression/expression_list.h>
#include <compiler/expression/function_call.h>
#include <compiler/analysis/code_error.h>
#include <compiler/statement/statement_list.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/parser/parser.h>
#include <util/logger.h>
#include <compiler/option.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/exp_statement.h>
#include <compiler/expression/parameter_expression.h>
#include <compiler/analysis/class_scope.h>
#include <util/atomic.h>
#include <util/util.h>
#include <runtime/base/class_info.h>
#include <runtime/base/type_conversions.h>
#include <runtime/base/builtin_functions.h>
#include <util/parser/hphp.tab.hpp>
#include <runtime/base/variable_serializer.h>
#include <runtime/base/zend/zend_string.h>
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/modifier_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/function_call.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/logger.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/exp_statement.h"
#include "hphp/compiler/expression/parameter_expression.h"
#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/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_needsRefTemp(false),
m_needsObjTemp(false), m_needsCheckMem(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_directInvoke(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_redeclaring(-1), m_inlineIndex(0), m_optFunction(0), m_nextID(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()) {
@@ -76,6 +78,12 @@ FunctionScope::FunctionScope(AnalysisResultConstPtr ar, bool method,
}
m_userAttributes[attrs[i]->getName()] = attrs[i]->getExp();
}
// Support for systemlib functions implemented in PHP
if (!m_method &&
m_userAttributes.find("__Overridable") != m_userAttributes.end()) {
setAllowOverride();
}
}
FunctionScope::FunctionScope(FunctionScopePtr orig,
@@ -83,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),
@@ -95,22 +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_needsRefTemp(orig->m_needsRefTemp),
m_needsObjTemp(orig->m_needsObjTemp),
m_needsCheckMem(orig->m_needsCheckMem),
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_nextID(0), m_yieldLabelCount(orig->m_yieldLabelCount),
m_yieldLabelGen(orig->m_yieldLabelGen) {
init(ar);
m_originalName = originalName;
setParamCounts(ar, m_minParam, m_maxParam);
@@ -199,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_needsRefTemp(false), m_needsObjTemp(false),
m_closureGenerator(false), m_noLSB(false), m_nextLSB(false),
m_directInvoke(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) {
@@ -276,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();
}
@@ -296,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();
}
@@ -305,8 +329,8 @@ bool FunctionScope::isVariableArgument() const {
return res;
}
bool FunctionScope::ignoreRedefinition() const {
return m_attribute & FileScope::IgnoreRedefinition;
bool FunctionScope::allowOverride() const {
return m_attribute & FileScope::AllowOverride;
}
bool FunctionScope::isReferenceVariableArgument() const {
@@ -331,39 +355,38 @@ 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());
}
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) {
@@ -376,8 +399,8 @@ void FunctionScope::setVariableArgument(int reference) {
}
}
void FunctionScope::setIgnoreRedefinition() {
m_attribute |= FileScope::IgnoreRedefinition;
void FunctionScope::setAllowOverride() {
m_attribute |= FileScope::AllowOverride;
}
bool FunctionScope::hasEffect() const {
@@ -410,13 +433,53 @@ bool FunctionScope::containsReference() const {
return m_attribute & FileScope::ContainsReference;
}
void FunctionScope::setContainsThis(bool f /* = true */) {
m_containsThis = f;
BlockScopePtr bs(this->getOuterScope());
while (bs && bs->is(BlockScope::FunctionScope)) {
FunctionScopePtr fs = static_pointer_cast<FunctionScope>(bs);
if (!fs->isClosure()) {
break;
}
fs->setContainsThis(f);
bs = bs->getOuterScope();
}
for (auto it = m_clonedTraitOuterScope.begin(); it != m_clonedTraitOuterScope.end(); it++) {
(*it)->setContainsThis(f);
}
}
void FunctionScope::setContainsBareThis(bool f, bool ref /* = false */) {
if (f) {
m_containsBareThis |= ref ? 2 : 1;
} else {
m_containsBareThis = 0;
}
BlockScopePtr bs(this->getOuterScope());
while (bs && bs->is(BlockScope::FunctionScope)) {
FunctionScopePtr fs = static_pointer_cast<FunctionScope>(bs);
if (!fs->isClosure()) {
break;
}
fs->setContainsBareThis(f, ref);
bs = bs->getOuterScope();
}
for (auto it = m_clonedTraitOuterScope.begin(); it != m_clonedTraitOuterScope.end(); it++) {
(*it)->setContainsBareThis(f, ref);
}
}
bool FunctionScope::hasImpl() const {
if (!isUserFunction()) {
return !isAbstract();
}
if (m_stmt) {
MethodStatementPtr stmt = dynamic_pointer_cast<MethodStatement>(m_stmt);
return stmt->getStmts();
return stmt->getStmts() != nullptr;
}
return false;
}
@@ -482,6 +545,7 @@ bool FunctionScope::mayUseVV() const {
return (inPseudoMain() ||
isVariableArgument() ||
isGenerator() ||
isAsync() ||
variables->getAttribute(VariableTable::ContainsDynamicVariable) ||
variables->getAttribute(VariableTable::ContainsExtract) ||
variables->getAttribute(VariableTable::ContainsCompact) ||
@@ -532,18 +596,6 @@ void FunctionScope::setPerfectVirtual() {
}
}
bool FunctionScope::needsTypeCheckWrapper() const {
for (int i = 0; i < m_maxParam; i++) {
if (isRefParam(i)) continue;
if (TypePtr spec = m_paramTypeSpecs[i]) {
if (Type::SameType(spec, m_paramTypes[i])) {
return true;
}
}
}
return false;
}
bool FunctionScope::needsClassParam() {
if (!isStatic()) return false;
ClassScopeRawPtr cls = getContainingClass();
@@ -619,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])) {
@@ -631,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);
@@ -739,16 +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());
StringData* sd = new StringData(value, len, AttachLiteral);
sd->setStatic();
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 =
@@ -801,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;
@@ -814,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;
}
@@ -888,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) {
@@ -1035,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(),
@@ -1049,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();
}
+55 -55
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,15 +14,16 @@
+----------------------------------------------------------------------+
*/
#ifndef __FUNCTION_SCOPE_H__
#define __FUNCTION_SCOPE_H__
#ifndef incl_HPHP_FUNCTION_SCOPE_H_
#define incl_HPHP_FUNCTION_SCOPE_H_
#include <compiler/expression/user_attribute.h>
#include <compiler/analysis/block_scope.h>
#include <compiler/option.h>
#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 <util/json.h>
#include <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,23 +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;
bool hasGeneratorAsBody() const;
MethodStatementRawPtr getOrigGenStmt() const;
FunctionScopeRawPtr getOrigGenFS() const;
void setNeedsRefTemp() { m_needsRefTemp = true; }
bool needsRefTemp() const { return m_needsRefTemp; }
void setNeedsObjTemp() { m_needsObjTemp = true; }
bool needsObjTemp() const { return m_needsObjTemp; }
void setNeedsCheckMem() { m_needsCheckMem = true; }
bool needsCheckMem() const { return m_needsCheckMem; }
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; }
@@ -161,7 +160,6 @@ public:
}
virtual std::string getId() const;
std::string getInjectionId() const;
int getRedeclaringId() const {
return m_redeclaring;
@@ -176,6 +174,13 @@ public:
m_volatile = false;
}
/**
* Tell this function about another outer scope that contains it.
*/
void addClonedTraitOuterScope(FunctionScopePtr scope) {
m_clonedTraitOuterScope.push_back(scope);
}
/**
* Get/set original name of the function, without case being lowered.
*/
@@ -218,10 +223,12 @@ public:
void setNeedsActRec();
/*
* If this is a builtin and can be redefined
* If this is a builtin (C++ or PHP) and can be redefined
*/
bool ignoreRedefinition() const;
void setIgnoreRedefinition();
bool allowOverride() const;
void setAllowOverride();
bool needsFinallyLocals() const;
/**
* Whether this function is a runtime helper function
@@ -237,16 +244,10 @@ public:
* Whether this function contains a usage of $this
*/
bool containsThis() const { return m_containsThis;}
void setContainsThis(bool f=true) { m_containsThis = f;}
void setContainsThis(bool f = true);
bool containsBareThis() const { return m_containsBareThis; }
bool containsRefThis() const { return m_containsBareThis & 2; }
void setContainsBareThis(bool f, bool ref = false) {
if (f) {
m_containsBareThis |= ref ? 2 : 1;
} else {
m_containsBareThis = 0;
}
}
void setContainsBareThis(bool f, bool ref = false);
/**
* How many parameters a caller should provide.
*/
@@ -256,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);
@@ -269,8 +272,6 @@ public:
void clearRetExprs();
void fixRetExprs();
bool needsTypeCheckWrapper() const;
void setOptFunction(FunctionOptPtr fn) { m_optFunction = fn; }
FunctionOptPtr getOptFunction() const { return m_optFunction; }
@@ -312,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; }
@@ -392,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);
@@ -400,8 +397,11 @@ public:
class FunctionInfo {
public:
FunctionInfo(int rva = -1) : m_maybeStatic(false), m_maybeRefReturn(false),
m_refVarArg(rva) { }
explicit FunctionInfo(int rva = -1)
: m_maybeStatic(false)
, m_maybeRefReturn(false)
, m_refVarArg(rva)
{}
bool isRefParam(int p) const {
if (m_refVarArg >= 0 && p >= m_refVarArg) return true;
@@ -441,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;
@@ -464,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
@@ -473,10 +472,8 @@ private:
unsigned m_inlineSameContext : 1;
unsigned m_contextSensitive : 1;
unsigned m_directInvoke : 1;
unsigned m_needsRefTemp : 1;
unsigned m_needsObjTemp : 1;
unsigned m_needsCheckMem : 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;
@@ -492,8 +489,11 @@ private:
ExpressionListPtr m_closureValues;
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;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // __FUNCTION_SCOPE_H__
#endif // incl_HPHP_FUNCTION_SCOPE_H_
+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
+20 -34
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,20 +14,21 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/live_dict.h>
#include <compiler/analysis/variable_table.h>
#include "hphp/compiler/analysis/live_dict.h"
#include <compiler/expression/expression.h>
#include <compiler/expression/assignment_expression.h>
#include <compiler/expression/simple_variable.h>
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include <compiler/statement/statement.h>
#include <compiler/statement/block_statement.h>
#include <compiler/statement/exp_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/statement_list.h>
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/block_statement.h"
#include "hphp/compiler/statement/exp_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
using namespace HPHP;
using std::vector;
@@ -326,10 +327,10 @@ void LiveDict::updateAccess(ExpressionPtr e) {
}
struct Colorizer {
Colorizer(int w) : toNode(w) {}
explicit Colorizer(int w) : toNode(w) {}
struct NodeInfo {
NodeInfo(int index) : originalIndex(index), size(0), color(-1) {}
explicit NodeInfo(int index) : originalIndex(index), size(0), color(-1) {}
int originalIndex;
int size;
int color;
@@ -359,7 +360,7 @@ struct Colorizer {
class NodeCmp {
public:
NodeCmp(const Colorizer *c) : m_c(c) {}
explicit NodeCmp(const Colorizer *c) : m_c(c) {}
bool operator()(int a, int b) {
const NodeInfo &n1 = m_c->nodes[a];
const NodeInfo &n2 = m_c->nodes[b];
@@ -461,25 +462,10 @@ bool LiveDict::color(TypePtr type) {
if (Type::SameType(type, e->getCPPType())) {
SimpleVariablePtr sv(
static_pointer_cast<SimpleVariable>(e));
bool isGenParam = false;
if (sv->getFunctionScope()->isGenerator()) {
// do not allow coalescing of symbols which are parameters/use vars
// in the generator (sym->isParameter() will be false b/c we are in
// the scope of the generator function)
FunctionScopeRawPtr origScope(sv->getFunctionScope()->getOrigGenFS());
assert(origScope);
Symbol *origSym =
origScope->getVariables()->getSymbol(sv->getName());
if (origSym &&
(origSym->isParameter() || origSym->isClosureVar())) {
isGenParam = true;
}
}
Symbol *sym = sv->getSymbol();
if (sym &&
!sym->isGlobal() &&
!sym->isParameter() &&
!isGenParam &&
!sym->isClosureVar() &&
!sym->isStatic() &&
!e->isThis()) {
@@ -623,9 +609,8 @@ public:
always_assert(e && e->is(Expression::KindOfSimpleVariable));
SimpleVariablePtr sv(static_pointer_cast<SimpleVariable>(e));
Symbol *sym = sv->getSymbol();
bool inGen = sv->getFunctionScope()->isGenerator();
if (!sym || sym->isGlobal() || sym->isStatic() || sym->isParameter() ||
sym->isClosureVar() || sv->isThis() || inGen) {
sym->isClosureVar() || sv->isThis()) {
continue;
}
@@ -638,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);
}
}
+6 -6
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,10 +14,10 @@
+----------------------------------------------------------------------+
*/
#ifndef __LIVE_DICT_H__
#define __LIVE_DICT_H__
#ifndef incl_HPHP_LIVE_DICT_H_
#define incl_HPHP_LIVE_DICT_H_
#include <compiler/analysis/dictionary.h>
#include "hphp/compiler/analysis/dictionary.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -26,7 +26,7 @@ namespace HPHP {
class LiveDict : public Dictionary {
public:
LiveDict(AliasManager &am) : Dictionary(am) {}
explicit LiveDict(AliasManager &am) : Dictionary(am) {}
/* Building the dictionary */
void build(MethodStatementPtr m);
void visit(ExpressionPtr e);
@@ -53,4 +53,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __LIVE_DICT_H__
#endif // incl_HPHP_LIVE_DICT_H_
+23 -20
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,19 +14,17 @@
+----------------------------------------------------------------------+
*/
#include "compiler/analysis/peephole.h"
#include "compiler/analysis/emitter.h"
#include "hphp/compiler/analysis/peephole.h"
#include "hphp/compiler/analysis/emitter.h"
#include "hphp/runtime/vm/preclass-emit.h"
namespace HPHP { namespace Compiler {
using VM::FuncEmitter;
using VM::UnitEmitter;
using VM::Offset;
static void collapseJmp(Offset* offsetPtr, Opcode* instr, Opcode* start) {
static void collapseJmp(Offset* offsetPtr, Op* instr, Op* start) {
if (offsetPtr) {
Opcode* dest = instr + *offsetPtr;
while (*dest == OpJmp && dest != instr) {
Op* dest = instr + *offsetPtr;
while (isUnconditionalJmp(*dest) && dest != instr) {
dest = start + instrJumpTarget(start, dest - start);
}
*offsetPtr = dest - instr;
@@ -45,10 +43,10 @@ Peephole::Peephole(UnitEmitter &ue, MetaInfoBuilder& metaInfo)
buildJumpTargets();
// Scan the bytecode linearly.
Opcode* start = ue.m_bc;
Opcode* prev = start;
Opcode* cur = prev + instrLen(prev);
Opcode* end = start + ue.m_bclen;
Op* start = (Op*)ue.m_bc;
Op* prev = start;
Op* cur = prev + instrLen(prev);
Op* end = start + ue.m_bclen;
/*
* TODO(1086005): we should try to minimize use of CGetL2/CGetL3.
@@ -93,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:
@@ -164,14 +162,19 @@ void Peephole::buildJumpTargets() {
}
// all jump targets are targets
for (Offset pos = 0; pos < (Offset)m_ue.m_bclen;
pos += instrLen(&m_ue.m_bc[pos])) {
Opcode* instr = &m_ue.m_bc[pos];
pos += instrLen((Op*)&m_ue.m_bc[pos])) {
Op* instr = (Op*)&m_ue.m_bc[pos];
if (isSwitch(*instr)) {
foreachSwitchTarget(instr, [&](Offset& o) {
m_jumpTargets.insert(pos + o);
});
} else if (*instr == OpIterBreak) {
uint32_t veclen = *(uint32_t *)(instr + 1);
assert(veclen > 0);
Offset target = *(Offset *)((uint32_t *)(instr + 1) + 2 * veclen + 1);
m_jumpTargets.insert(pos + target);
} else {
Offset target = instrJumpTarget(m_ue.m_bc, pos);
Offset target = instrJumpTarget((Op*)m_ue.m_bc, pos);
if (target != InvalidAbsoluteOffset) {
m_jumpTargets.insert(target);
}
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -34,8 +34,8 @@
#ifndef incl_HPHP_COMPILER_ANALYSIS_PEEPHOLE_H_
#define incl_HPHP_COMPILER_ANALYSIS_PEEPHOLE_H_
#include "runtime/vm/unit.h"
#include "runtime/vm/func.h"
#include "hphp/runtime/vm/unit.h"
#include "hphp/runtime/vm/func.h"
namespace HPHP { namespace Compiler {
@@ -43,14 +43,14 @@ class MetaInfoBuilder;
class Peephole {
public:
Peephole(VM::UnitEmitter& ue, MetaInfoBuilder& metaInfo);
Peephole(UnitEmitter& ue, MetaInfoBuilder& metaInfo);
private:
void buildFuncTargets(VM::FuncEmitter* fe);
void buildFuncTargets(FuncEmitter* fe);
void buildJumpTargets();
VM::UnitEmitter& m_ue;
hphp_hash_set<VM::Offset> m_jumpTargets;
UnitEmitter& m_ue;
hphp_hash_set<Offset> m_jumpTargets;
};
}}
+29 -29
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,22 +14,22 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/ref_dict.h>
#include "hphp/compiler/analysis/ref_dict.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/function_scope.h"
#include <compiler/expression/expression.h>
#include <compiler/expression/assignment_expression.h>
#include <compiler/expression/binary_op_expression.h>
#include <compiler/expression/simple_variable.h>
#include "hphp/compiler/expression/expression.h"
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/binary_op_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include <compiler/statement/statement.h>
#include <compiler/statement/block_statement.h>
#include <compiler/statement/exp_statement.h>
#include <compiler/statement/method_statement.h>
#include <compiler/statement/statement_list.h>
#include "hphp/compiler/statement/statement.h"
#include "hphp/compiler/statement/block_statement.h"
#include "hphp/compiler/statement/exp_statement.h"
#include "hphp/compiler/statement/method_statement.h"
#include "hphp/compiler/statement/statement_list.h"
#include <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)) {
+7 -7
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,17 +14,17 @@
+----------------------------------------------------------------------+
*/
#ifndef __REF_DICT_H__
#define __REF_DICT_H__
#ifndef incl_HPHP_REF_DICT_H_
#define incl_HPHP_REF_DICT_H_
#include <compiler/analysis/dictionary.h>
#include "hphp/compiler/analysis/dictionary.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
class RefDict : public Dictionary {
public:
RefDict(AliasManager &am) : Dictionary(am), first_pass(true) {}
explicit RefDict(AliasManager &am) : Dictionary(am), first_pass(true) {}
/* Building the dictionary */
void build(MethodStatementPtr m);
@@ -52,7 +52,7 @@ private:
class RefDictWalker : public ControlFlowGraphWalker {
public:
RefDictWalker(ControlFlowGraph *g) :
explicit RefDictWalker(ControlFlowGraph *g) :
ControlFlowGraphWalker(g), first_pass(true) {}
void walk() { ControlFlowGraphWalker::walk(*this); }
int after(ConstructRawPtr cp);
@@ -63,4 +63,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __REF_DICT_H__
#endif // incl_HPHP_REF_DICT_H_
+35 -47
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,23 +14,24 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/symbol_table.h>
#include <compiler/analysis/type.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/function_scope.h>
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include <compiler/expression/constant_expression.h>
#include <compiler/expression/expression_list.h>
#include <compiler/expression/parameter_expression.h>
#include <compiler/expression/simple_variable.h>
#include "hphp/compiler/expression/assignment_expression.h"
#include "hphp/compiler/expression/constant_expression.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/expression/parameter_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#include <runtime/base/class_info.h>
#include <runtime/base/complex_types.h>
#include <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 <util/logger.h>
#include "hphp/util/logger.h"
using namespace HPHP;
@@ -64,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();
}
@@ -284,9 +285,9 @@ void Symbol::serializeParam(JSON::DocTarget::OutputStream &out) const {
assert(valueExp);
const string &init = ExtractInitializer(out.analysisResult(), valueExp);
if (!init.empty()) out << init;
else out << JSON::Null;
else out << JSON::Null();
} else {
out << JSON::Null;
out << JSON::Null();
}
ms.done();
@@ -295,20 +296,18 @@ void Symbol::serializeParam(JSON::DocTarget::OutputStream &out) const {
static inline std::string ExtractDocComment(ExpressionPtr e) {
if (!e) return "";
switch (e->getKindOf()) {
case Expression::KindOfAssignmentExpression:
return ExtractDocComment(e->getNthExpr(0));
case Expression::KindOfSimpleVariable:
{
SimpleVariablePtr sv(
static_pointer_cast<SimpleVariable>(e));
return sv->getDocComment();
}
case Expression::KindOfConstantExpression:
{
ConstantExpressionPtr ce(
static_pointer_cast<ConstantExpression>(e));
return ce->getDocComment();
}
case Expression::KindOfAssignmentExpression: {
AssignmentExpressionPtr ae(static_pointer_cast<AssignmentExpression>(e));
return ExtractDocComment(ae->getVariable());
}
case Expression::KindOfSimpleVariable: {
SimpleVariablePtr sv(static_pointer_cast<SimpleVariable>(e));
return sv->getDocComment();
}
case Expression::KindOfConstantExpression: {
ConstantExpressionPtr ce(static_pointer_cast<ConstantExpression>(e));
return ce->getDocComment();
}
default: return "";
}
return "";
@@ -337,9 +336,9 @@ void Symbol::serializeClassVar(JSON::DocTarget::OutputStream &out) const {
assert(initExp);
const string &init = ExtractInitializer(out.analysisResult(), initExp);
if (!init.empty()) out << init;
else out << JSON::Null;
else out << JSON::Null();
} else {
out << JSON::Null;
out << JSON::Null();
}
const string &docs = ExtractDocComment(
@@ -521,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);
@@ -596,7 +584,7 @@ void SymbolTable::countTypes(std::map<std::string, int> &counts) {
}
string SymbolTable::getEscapedText(Variant v, int &len) {
VariableSerializer vs(VariableSerializer::Serialize);
VariableSerializer vs(VariableSerializer::Type::Serialize);
String str = vs.serialize(v, true);
len = str.length();
string output = Util::escapeStringForCPP(str.data(), len);
+20 -20
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,13 +14,14 @@
+----------------------------------------------------------------------+
*/
#ifndef __SYMBOL_TABLE_H__
#define __SYMBOL_TABLE_H__
#ifndef incl_HPHP_SYMBOL_TABLE_H_
#define incl_HPHP_SYMBOL_TABLE_H_
#include <compiler/hphp.h>
#include <util/json.h>
#include <util/util.h>
#include <util/lock.h>
#include "hphp/compiler/hphp.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; }
@@ -185,7 +184,7 @@ private:
std::string m_name;
unsigned int m_hash;
union {
unsigned m_flags_val;
uint32_t m_flags_val;
struct {
/* internal */
unsigned m_declaration_set : 1;
@@ -196,7 +195,6 @@ private:
/* common */
unsigned m_system : 1;
unsigned m_sep : 1;
/* ConstantTable */
unsigned m_dynamic : 1;
@@ -227,7 +225,13 @@ private:
unsigned m_stashedVal : 1;
unsigned m_reseated : 1;
} m_flags;
};
static_assert(
sizeof(m_flags_val) == sizeof(m_flags),
"m_flags_val must cover all the flags");
ConstructPtr m_declaration;
ConstructPtr m_value;
TypePtr m_coerced;
@@ -244,7 +248,7 @@ private:
class SymParamWrapper : public JSON::DocTarget::ISerializable {
public:
SymParamWrapper(const Symbol* sym) : m_sym(sym) {
explicit SymParamWrapper(const Symbol* sym) : m_sym(sym) {
assert(sym);
}
virtual void serialize(JSON::DocTarget::OutputStream &out) const {
@@ -256,7 +260,7 @@ private:
class SymClassVarWrapper : public JSON::DocTarget::ISerializable {
public:
SymClassVarWrapper(const Symbol* sym) : m_sym(sym) {
explicit SymClassVarWrapper(const Symbol* sym) : m_sym(sym) {
assert(sym);
}
virtual void serialize(JSON::DocTarget::OutputStream &out) const {
@@ -269,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;
@@ -335,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.
*/
@@ -382,4 +382,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __SYMBOL_TABLE_H__
#endif // incl_HPHP_SYMBOL_TABLE_H_
+69 -26
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,12 +14,14 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/type.h>
#include <compiler/code_generator.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/expression/expression.h>
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/analysis/analysis_result.h"
#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/vm/runtime.h"
#include <boost/format.hpp>
using namespace HPHP;
@@ -35,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 ));
@@ -49,38 +52,65 @@ TypePtr Type::Any (new Type(Type::KindOfAny ));
TypePtr Type::Some (new Type(Type::KindOfSome ));
Type::TypePtrMap Type::s_TypeHintTypes;
Type::TypePtrMap Type::s_HHTypeHintTypes;
void Type::InitTypeHintMap() {
assert(s_TypeHintTypes.empty());
assert(s_HHTypeHintTypes.empty());
s_TypeHintTypes["array"] = Type::Array;
if (Option::EnableHipHopSyntax) {
s_TypeHintTypes["bool"] = Type::Boolean;
s_TypeHintTypes["boolean"] = Type::Boolean;
s_TypeHintTypes["int"] = Type::Int64;
s_TypeHintTypes["integer"] = Type::Int64;
s_TypeHintTypes["real"] = Type::Double;
s_TypeHintTypes["double"] = Type::Double;
s_TypeHintTypes["float"] = Type::Double;
s_TypeHintTypes["string"] = Type::String;
}
s_TypeHintTypes["resource"] = Type::Resource;
s_TypeHintTypes["callable"] = Type::Variant;
s_HHTypeHintTypes["array"] = Type::Array;
s_HHTypeHintTypes["bool"] = Type::Boolean;
s_HHTypeHintTypes["boolean"] = Type::Boolean;
s_HHTypeHintTypes["int"] = Type::Int64;
s_HHTypeHintTypes["integer"] = Type::Int64;
s_HHTypeHintTypes["real"] = Type::Double;
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() {
return s_TypeHintTypes;
const Type::TypePtrMap &Type::GetTypeHintTypes(bool hhType) {
return hhType ? s_HHTypeHintTypes : s_TypeHintTypes;
}
void Type::ResetTypeHintTypes() {
s_TypeHintTypes.clear();
s_HHTypeHintTypes.clear();
}
TypePtr Type::CreateObjectType(const std::string &classname) {
return TypePtr(new Type(KindOfObject, classname));
TypePtr Type::CreateObjectType(const std::string &clsname) {
// For interfaces that support primitive types, we're pessimistic and
// we treat it as a Variant
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));
}
TypePtr Type::GetType(KindOf kindOf,
const std::string &clsname /* = "" */) {
TypePtr Type::GetType(KindOf kindOf, const std::string &clsname /* = "" */) {
assert(kindOf);
if (!clsname.empty()) return TypePtr(new Type(kindOf, clsname));
if (!clsname.empty()) {
// For interfaces that support primitive types we're pessimistic and
// we treat it as a Variant
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));
}
switch (kindOf) {
case KindOfBoolean: return Type::Boolean;
@@ -91,6 +121,7 @@ TypePtr Type::GetType(KindOf kindOf,
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;
@@ -177,6 +208,7 @@ bool Type::IsMappedToVariant(TypePtr t) {
case KindOfString :
case KindOfArray :
case KindOfObject :
case KindOfResource:
return false;
default: break;
}
@@ -245,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 ||
@@ -380,6 +413,7 @@ bool Type::HasFastCastMethod(TypePtr t) {
case Type::KindOfString:
case Type::KindOfArray:
case Type::KindOfObject:
case Type::KindOfResource:
return true;
default: break;
}
@@ -425,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);
@@ -520,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
@@ -598,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:
@@ -619,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 "";
@@ -636,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";
@@ -684,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;
+13 -10
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,13 +14,13 @@
+----------------------------------------------------------------------+
*/
#ifndef __TYPE_H__
#define __TYPE_H__
#ifndef incl_HPHP_TYPE_H_
#define incl_HPHP_TYPE_H_
#include <compiler/hphp.h>
#include <util/json.h>
#include <util/case_insensitive.h>
#include <runtime/base/types.h>
#include "hphp/compiler/hphp.h"
#include "hphp/compiler/json.h"
#include "hphp/util/functional.h"
#include "hphp/runtime/base/types.h"
class TestCodeRun;
@@ -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;
@@ -102,7 +104,7 @@ public:
static TypePtr Some;
typedef hphp_string_imap<TypePtr> TypePtrMap;
static const TypePtrMap &GetTypeHintTypes();
static const TypePtrMap &GetTypeHintTypes(bool hhType);
/**
* Uncertain types: types that are ambiguous yet.
@@ -201,7 +203,7 @@ public:
/**
* KindOf testing.
*/
Type(KindOf kindOf);
explicit Type(KindOf kindOf);
bool is(KindOf kindOf) const { return m_kindOf == kindOf;}
bool isExactType() const { return IsExactType(m_kindOf); }
bool mustBe(KindOf kindOf) const { return !(m_kindOf & ~kindOf); }
@@ -267,6 +269,7 @@ private:
static void ResetTypeHintTypes();
static TypePtrMap s_TypeHintTypes;
static TypePtrMap s_HHTypeHintTypes;
const KindOf m_kindOf;
const std::string m_name;
@@ -274,4 +277,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __TYPE_H__
#endif // incl_HPHP_TYPE_H_
+48 -30
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,24 +14,25 @@
+----------------------------------------------------------------------+
*/
#include <compiler/analysis/variable_table.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/type.h>
#include <compiler/code_generator.h>
#include <compiler/expression/modifier_expression.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/expression/simple_variable.h>
#include <compiler/builtin_symbols.h>
#include <compiler/option.h>
#include <compiler/expression/simple_function_call.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/expression/static_member_expression.h>
#include <runtime/base/class_info.h>
#include <util/util.h>
#include <util/parser/location.h>
#include <util/parser/parser.h>
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/expression/modifier_expression.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/builtin_symbols.h"
#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/util/util.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
@@ -225,7 +237,7 @@ ConstructPtr VariableTable::getStaticInitVal(string varName) {
bool VariableTable::setStaticInitVal(string varName,
ConstructPtr value) {
Symbol *sym = addSymbol(varName);
bool exists = sym->getStaticInitVal();
bool exists = (sym->getStaticInitVal() != nullptr);
sym->setStaticInitVal(value);
return exists;
}
@@ -239,7 +251,7 @@ ConstructPtr VariableTable::getClassInitVal(string varName) {
bool VariableTable::setClassInitVal(string varName, ConstructPtr value) {
Symbol *sym = addSymbol(varName);
bool exists = sym->getClassInitVal();
bool exists = (sym->getClassInitVal() != nullptr);
sym->setClassInitVal(value);
return exists;
}
@@ -290,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);
@@ -415,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()) {
@@ -738,7 +756,7 @@ static bool by_location(const VariableTable::StaticGlobalInfoPtr &p1,
const VariableTable::StaticGlobalInfoPtr &p2) {
ConstructRawPtr d1 = p1->sym->getDeclaration();
ConstructRawPtr d2 = p2->sym->getDeclaration();
if (!d1) return d2;
if (!d1) return !!d2;
if (!d2) return false;
return d1->getLocation()->compare(d2->getLocation().get()) < 0;
}
+10 -9
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,12 +14,13 @@
+----------------------------------------------------------------------+
*/
#ifndef __VARIABLE_TABLE_H__
#define __VARIABLE_TABLE_H__
#ifndef incl_HPHP_VARIABLE_TABLE_H_
#define incl_HPHP_VARIABLE_TABLE_H_
#include <compiler/analysis/symbol_table.h>
#include <compiler/statement/statement.h>
#include <compiler/analysis/class_scope.h>
#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 {
///////////////////////////////////////////////////////////////////////////////
@@ -100,7 +101,7 @@ public:
}
public:
VariableTable(BlockScope &blockScope);
explicit VariableTable(BlockScope &blockScope);
/**
* Get/set attributes.
@@ -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
@@ -353,4 +354,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __VARIABLE_TABLE_H__
#endif // incl_HPHP_VARIABLE_TABLE_H_
+274 -461
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,24 +14,27 @@
+----------------------------------------------------------------------+
*/
#include <compiler/builtin_symbols.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/statement/statement_list.h>
#include <compiler/analysis/type.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/expression/modifier_expression.h>
#include <compiler/option.h>
#include <compiler/parser/parser.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/analysis/constant_table.h>
#include <util/parser/hphp.tab.hpp>
#include <runtime/base/class_info.h>
#include <runtime/base/program_functions.h>
#include <runtime/base/array/array_iterator.h>
#include <util/logger.h>
#include <util/util.h>
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/expression/modifier_expression.h"
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/compiler/analysis/constant_table.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>
using namespace HPHP;
@@ -46,39 +49,8 @@ using namespace HPHP;
///////////////////////////////////////////////////////////////////////////////
bool BuiltinSymbols::Loaded = false;
bool BuiltinSymbols::NoSuperGlobals = false;
StringBag BuiltinSymbols::s_strings;
namespace HPHP {
#define EXT_TYPE 4
#include <system/ext.inc>
#undef EXT_TYPE
}
const char *BuiltinSymbols::ExtensionFunctions[] = {
#define S(n) (const char *)n
#define T(t) (const char *)Type::KindOf ## t
#define EXT_TYPE 0
#include <system/ext.inc>
nullptr,
};
#undef EXT_TYPE
const char *BuiltinSymbols::ExtensionConsts[] = {
#define EXT_TYPE 1
#include <system/ext.inc>
nullptr,
};
#undef EXT_TYPE
const char *BuiltinSymbols::ExtensionClasses[] = {
#define EXT_TYPE 2
#include <system/ext.inc>
nullptr,
};
#undef EXT_TYPE
StringToFunctionScopePtrMap BuiltinSymbols::s_functions;
AnalysisResultPtr BuiltinSymbols::s_systemAr;
const char *const BuiltinSymbols::GlobalNames[] = {
"HTTP_RAW_POST_DATA",
@@ -100,6 +72,7 @@ const char *BuiltinSymbols::SystemClasses[] = {
"exception",
"arrayaccess",
"iterator",
"collections",
"reflection",
"splobjectstorage",
"directory",
@@ -112,11 +85,7 @@ const char *BuiltinSymbols::SystemClasses[] = {
nullptr
};
StringToClassScopePtrMap BuiltinSymbols::s_classes;
VariableTablePtr BuiltinSymbols::s_variables;
ConstantTablePtr BuiltinSymbols::s_constants;
StringToTypePtrMap BuiltinSymbols::s_superGlobals;
void *BuiltinSymbols::s_handle_main = nullptr;
///////////////////////////////////////////////////////////////////////////////
@@ -125,462 +94,307 @@ int BuiltinSymbols::NumGlobalNames() {
sizeof(BuiltinSymbols::GlobalNames[0]);
}
void BuiltinSymbols::ParseExtFunctions(AnalysisResultPtr ar, const char **p,
bool sep) {
while (*p) {
FunctionScopePtr f = ParseExtFunction(ar, p);
if (sep) {
f->setSepExtension();
}
assert(!s_functions[f->getName()]);
s_functions[f->getName()] = f;
static TypePtr typePtrFromDataType(DataType dt, TypePtr unknown) {
switch (dt) {
case KindOfNull: return Type::Null;
case KindOfBoolean: return Type::Boolean;
case KindOfInt64: return Type::Int64;
case KindOfDouble: return Type::Double;
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;
}
}
void BuiltinSymbols::ParseExtConsts(AnalysisResultPtr ar, const char **p,
bool sep) {
while (*p) {
const char *name = *p++;
TypePtr type = ParseType(p);
s_constants->add(name, type, ExpressionPtr(), ar, ConstructPtr());
if (sep) {
s_constants->setSepExtension(name);
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;
bool isMethod = cls != ClassInfo::GetSystem();
FunctionScopePtr f(new FunctionScope(isMethod,
method->name.data(),
attrs & ClassInfo::IsReference));
int reqCount = 0, totalCount = 0;
for(auto it = method->parameters.begin();
it != method->parameters.end(); ++it) {
const ClassInfo::ParameterInfo *pinfo = *it;
if (!pinfo->value || !pinfo->value[0]) {
++reqCount;
}
++totalCount;
}
f->setParamCounts(ar, reqCount, totalCount);
int idx = 0;
for(auto it = method->parameters.begin();
it != method->parameters.end(); ++it, ++idx) {
const ClassInfo::ParameterInfo *pinfo = *it;
f->setParamName(idx, pinfo->name);
if (pinfo->attribute & ClassInfo::IsReference) {
f->setRefParam(idx);
}
f->setParamType(ar, idx, typePtrFromDataType(pinfo->argType, Type::Any));
if (pinfo->valueLen) {
f->setParamDefault(idx, pinfo->value, pinfo->valueLen,
std::string(pinfo->valueText, pinfo->valueTextLen));
}
}
}
TypePtr BuiltinSymbols::ParseType(const char **&p) {
const char *clsname = nullptr;
Type::KindOf ktype = (Type::KindOf)(long)(*p++);
if (ktype == CLASS_TYPE) {
clsname = *p++;
}
TypePtr type;
if (clsname) {
type = Type::CreateObjectType(clsname);
} else if (ktype != Type::KindOfVoid) {
type = Type::GetType(ktype);
}
return type;
}
void BuiltinSymbols::ParseExtClasses(AnalysisResultPtr ar, const char **p,
bool sep) {
while (*p) {
// Parse name
const char *cname = *p++;
// Parse parent
const char *cparent = *p++;
if (!cparent) cparent = "";
// Parse list of interfaces
vector<string> ifaces;
while (*p) ifaces.push_back(*p++);
p++;
// Parse methods
FunctionScopePtrVec methods;
while (*p) {
FunctionScopePtr fs = ParseExtFunction(ar, p, true);
if (sep) {
fs->setSepExtension();
}
int flags = (int)(int64_t)(*p++);
if (flags & ClassInfo::IsAbstract) {
fs->addModifier(T_ABSTRACT);
}
int vismod = 0;
if (flags & ClassInfo::IsProtected) {
vismod = T_PROTECTED;
} else if (flags & ClassInfo::IsPrivate) {
vismod = T_PRIVATE;
}
fs->addModifier(vismod);
if (flags & ClassInfo::IsStatic) {
fs->addModifier(T_STATIC);
}
methods.push_back(fs);
}
if (cparent && *cparent && (ifaces.empty() || ifaces[0] != cparent)) {
ifaces.insert(ifaces.begin(), cparent);
}
ClassScopePtr cl(new ClassScope(ar, cname, cparent, ifaces, methods));
for (uint i = 0; i < methods.size(); ++i) {
methods[i]->setOuterScope(cl);
}
p++;
// Parse properties
while (*p) {
int flags = (int)(int64_t)(*p++);
ModifierExpressionPtr modifiers(
new ModifierExpression(BlockScopePtr(), LocationPtr()));
if (flags & ClassInfo::IsProtected) {
modifiers->add(T_PROTECTED);
} else if (flags & ClassInfo::IsPrivate) {
modifiers->add(T_PRIVATE);
}
if (flags & ClassInfo::IsStatic) {
modifiers->add(T_STATIC);
}
const char *name = *p++;
TypePtr type = ParseType(p);
cl->getVariables()->add(name, type, false, ar, ExpressionPtr(), modifiers);
}
p++;
// Parse consts
while (*p) {
const char *name = *p++;
TypePtr type = ParseType(p);
cl->getConstants()->add(name, type, ExpressionPtr(), ar, ConstructPtr());
}
p++;
int flags = (int)(int64_t)(*p++);
cl->setClassInfoAttribute(flags);
if (flags & ClassInfo::HasDocComment) {
cl->setDocComment(*p++);
}
cl->setSystem();
if (sep) {
cl->setSepExtension();
}
s_classes[cl->getName()] = cl;
}
}
FunctionScopePtr BuiltinSymbols::ParseExtFunction(AnalysisResultPtr ar,
const char** &p, bool method /* = false */) {
const char *name = *p++;
TypePtr retType = ParseType(p);
bool reference = *p++;
int minParam = -1;
int maxParam = 0;
const char **arg = p;
while (*arg) {
/* name */ arg++;
ParseType(arg);
const char *argDefault = *arg++;
/* const char *argDefaultLen = */ arg++;
/* const char *argDefaultText = */ arg++;
/* bool argReference = */ arg++;
if (argDefault && minParam < 0) {
minParam = maxParam;
}
maxParam++;
}
if (minParam < 0) minParam = maxParam;
FunctionScopePtr f(new FunctionScope(method, name, reference));
f->setParamCounts(ar, minParam, maxParam);
if (retType) {
f->setReturnType(ar, retType);
if (method->returnType != KindOfNull) {
f->setReturnType(ar, typePtrFromDataType(method->returnType,
Type::Variant));
}
int index = 0;
const char *paramName = nullptr;
while ((paramName = *p++ /* argName */)) {
TypePtr argType = ParseType(p);
const char *argDefault = *p++;
const char *argDefaultLen = *p++;
const char *argDefaultText = *p++;
bool argReference = *p++;
f->setClassInfoAttribute(attrs);
f->setDocComment(method->docComment);
f->setParamName(index, paramName);
if (argReference) f->setRefParam(index);
f->setParamType(ar, index, argType);
if (argDefault) f->setParamDefault(index, argDefault,
(int64_t)argDefaultLen,
argDefaultText);
index++;
if (!isMethod && (attrs & ClassInfo::HasOptFunction)) {
// Legacy optimization functions
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(s_is_callable)) {
f->setOptFunction(hphp_opt_is_callable);
} else if (method->name.same(s_call_user_func_array)) {
f->setOptFunction(hphp_opt_call_user_func);
}
}
int flags = (int)(int64_t)(*p++);
f->setClassInfoAttribute(flags);
if (flags & ClassInfo::HasDocComment) {
f->setDocComment(*p++);
}
if (flags & ClassInfo::HasOptFunction) {
f->setOptFunction((FunctionOptPtr)(*p++));
if (isMethod) {
if (attrs & ClassInfo::IsProtected) {
f->addModifier(T_PROTECTED);
} else if (attrs & ClassInfo::IsPrivate) {
f->addModifier(T_PRIVATE);
}
if (attrs & ClassInfo::IsStatic) {
f->addModifier(T_STATIC);
}
}
// This block of code is not needed, if BlockScope directly takes flags.
if (flags & ClassInfo::MixedVariableArguments) {
if (attrs & ClassInfo::MixedVariableArguments) {
f->setVariableArgument(-1);
} else if (flags & ClassInfo::RefVariableArguments) {
} else if (attrs & ClassInfo::RefVariableArguments) {
f->setVariableArgument(1);
} else if (flags & ClassInfo::VariableArguments) {
} else if (attrs & ClassInfo::VariableArguments) {
f->setVariableArgument(0);
}
if (flags & ClassInfo::NoEffect) {
if (attrs & ClassInfo::NoEffect) {
f->setNoEffect();
}
if (flags & ClassInfo::FunctionIsFoldable) {
if (attrs & ClassInfo::FunctionIsFoldable) {
f->setIsFoldable();
}
if (flags & ClassInfo::ContextSensitive) {
if (attrs & ClassInfo::ContextSensitive) {
f->setContextSensitive(true);
}
if (flags & ClassInfo::NeedsActRec) {
if (attrs & ClassInfo::NeedsActRec) {
f->setNeedsActRec();
}
if ((flags & ClassInfo::IgnoreRedefinition) && !method) {
f->setIgnoreRedefinition();
if ((attrs & ClassInfo::AllowOverride) && !isMethod) {
f->setAllowOverride();
}
FunctionScope::RecordFunctionInfo(f->getName(), f);
return f;
}
FunctionScopePtr BuiltinSymbols::ParseHelperFunction(AnalysisResultPtr ar,
const char** &p) {
FunctionScopePtr f = ParseExtFunction(ar, p);
f->setHelperFunction();
return f;
}
bool BuiltinSymbols::LoadSepExtensionSymbols(AnalysisResultPtr ar,
const std::string &name,
const std::string &soname) {
string mapname = name + "_map";
const char ***symbols = nullptr;
// If we linked with .a, the symbol is already in main program.
if (s_handle_main == nullptr) {
s_handle_main = dlopen(nullptr, RTLD_NOW | RTLD_GLOBAL);
if (!s_handle_main) {
const char *error = dlerror();
Logger::Error("Unable to load main program's symbols: %s",
error ? error : "(unknown)");
void BuiltinSymbols::ImportExtFunctions(AnalysisResultPtr ar,
ClassInfo *cls) {
const ClassInfo::MethodVec &methods = cls->getMethodsVec();
for (auto it = methods.begin(); it != methods.end(); ++it) {
if (((*it)->attribute & ClassInfo::ZendCompat) &&
!Option::EnableZendCompat) {
continue;
}
}
if (s_handle_main) {
symbols = (const char ***)dlsym(s_handle_main, mapname.c_str());
}
// Otherwise, look for .so to load it.
void *handle = nullptr;
if (!symbols) {
handle = dlopen(soname.c_str(), RTLD_NOW | RTLD_GLOBAL);
if (!handle) {
const char *error = dlerror();
Logger::Error("Unable to load %s: %s", soname.c_str(),
error ? error : "(unknown)");
return false;
}
symbols = (const char ***)dlsym(handle, mapname.c_str());
if (!symbols) {
Logger::Error("Unable to find %s in %s", mapname.c_str(),
soname.c_str());
dlclose(handle);
return false;
}
}
ParseExtFunctions(ar, symbols[0], true);
ParseExtConsts (ar, symbols[1], true);
ParseExtClasses (ar, symbols[2], true);
if (handle) {
/*
Not closing for now, because it may have set an object allocator,
which would then fail next time its used.
I think the object allocators should be fixed instead - one per size,
rather than one per class, then this issue wouldnt occur
*/
// dlclose(handle);
}
return true;
}
void BuiltinSymbols::Parse(AnalysisResultPtr ar,
const std::string& phpBaseName,
const std::string& phpFileName) {
const char *baseName = s_strings.add(phpBaseName.c_str());
const char *fileName = s_strings.add(phpFileName.c_str());
try {
Scanner scanner(fileName, Option::ScannerType);
Compiler::Parser parser(scanner, baseName, ar);
if (!parser.parse()) {
Logger::Error("Unable to parse file %s: %s", fileName,
parser.getMessage().c_str());
assert(false);
}
} catch (FileOpenException &e) {
Logger::Error("%s", e.getMessage().c_str());
FunctionScopePtr f = ImportFunctionScopePtr(ar, cls, *it);
ar->addSystemFunction(f);
}
}
bool BuiltinSymbols::Load(AnalysisResultPtr ar, bool extOnly /* = false */) {
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);
vec.push_back(f);
}
}
void BuiltinSymbols::ImportExtProperties(AnalysisResultPtr ar,
VariableTablePtr dest,
ClassInfo *cls) {
ClassInfo::PropertyVec src = cls->getPropertiesVec();
for (auto it = src.begin(); it != src.end(); ++it) {
ClassInfo::PropertyInfo *pinfo = *it;
int attrs = pinfo->attribute;
ModifierExpressionPtr modifiers(
new ModifierExpression(BlockScopePtr(), LocationPtr()));
if (attrs & ClassInfo::IsPrivate) {
modifiers->add(T_PRIVATE);
} else if (attrs & ClassInfo::IsProtected) {
modifiers->add(T_PROTECTED);
}
if (attrs & ClassInfo::IsStatic) {
modifiers->add(T_STATIC);
}
dest->add(pinfo->name.data(),
typePtrFromDataType(pinfo->type, Type::Variant),
false, ar, ExpressionPtr(), modifiers);
}
}
void BuiltinSymbols::ImportExtConstants(AnalysisResultPtr ar,
ConstantTablePtr dest,
ClassInfo *cls) {
ClassInfo::ConstantVec src = cls->getConstantsVec();
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, etc.) it'll be a String.
ClassInfo::ConstantInfo *cinfo = *it;
dest->add(cinfo->name.data(),
cinfo->isDeferred() ?
(cinfo->isCallback() ? Type::Object : Type::String) :
typePtrFromDataType(cinfo->getValue().getType(), Type::Variant),
ExpressionPtr(), ar, ConstructPtr());
}
}
ClassScopePtr BuiltinSymbols::ImportClassScopePtr(AnalysisResultPtr ar,
ClassInfo *cls) {
FunctionScopePtrVec methods;
ImportExtMethods(ar, methods, cls);
ClassInfo::InterfaceVec ifaces = cls->getInterfacesVec();
String parent = cls->getParentClass();
std::vector<std::string> stdIfaces;
if (!parent.empty() && (ifaces.empty() || ifaces[0] != parent)) {
stdIfaces.push_back(parent.data());
}
for (auto it = ifaces.begin(); it != ifaces.end(); ++it) {
stdIfaces.push_back(it->data());
}
ClassScopePtr cl(new ClassScope(ar, cls->getName().data(), parent.data(),
stdIfaces, methods));
for (uint i = 0; i < methods.size(); ++i) {
methods[i]->setOuterScope(cl);
}
ImportExtProperties(ar, cl->getVariables(), cls);
ImportExtConstants(ar, cl->getConstants(), cls);
int attrs = cls->getAttribute();
cl->setClassInfoAttribute(attrs);
cl->setDocComment(cls->getDocComment());
cl->setSystem();
return cl;
}
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);
ar->addSystemClass(cl);
}
}
bool BuiltinSymbols::Load(AnalysisResultPtr ar) {
if (Loaded) return true;
Loaded = true;
// load extension functions first, so system/classes may call them
ParseExtFunctions(ar, ExtensionFunctions, false);
AnalysisResultPtr ar2 = AnalysisResultPtr(new AnalysisResult());
s_variables = VariableTablePtr(new VariableTable(*ar2.get()));
s_constants = ConstantTablePtr(new ConstantTable(*ar2.get()));
if (g_context.isNull()) init_thread_locals();
ClassInfo::Load();
// parse all PHP files under system/classes
if (!extOnly) {
ar = AnalysisResultPtr(new AnalysisResult());
ar->loadBuiltinFunctions();
string slib = systemlib_path();
if (slib.empty()) {
for (const char **cls = SystemClasses; *cls; cls++) {
string phpBaseName = "/system/classes/";
phpBaseName += *cls;
phpBaseName += ".php";
Parse(ar, phpBaseName, Option::GetSystemRoot() + phpBaseName);
}
} else {
Parse(ar, slib, slib);
}
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];
}
}
} else {
NoSuperGlobals = true;
}
// load extension functions first, so system/php may call them
ImportExtFunctions(ar, ClassInfo::GetSystem());
ConstantTablePtr cns = ar->getConstants();
// load extension constants, classes and dynamics
ParseExtConsts(ar, ExtensionConsts, false);
ParseExtClasses(ar, ExtensionClasses, false);
for (unsigned int i = 0; i < Option::SepExtensions.size(); i++) {
Option::SepExtensionOptions &options = Option::SepExtensions[i];
string soname = options.soname;
if (soname.empty()) {
soname = string("lib") + options.name + ".so";
}
if (!options.lib_path.empty()) {
soname = options.lib_path + "/" + soname;
}
if (!LoadSepExtensionSymbols(ar, options.name, soname)) {
return false;
}
ImportExtConstants(ar, cns, ClassInfo::GetSystem());
ImportExtClasses(ar);
Array constants = ClassInfo::GetSystemConstants();
LocationPtr loc(new Location);
for (ArrayIter it = constants.begin(); it; ++it) {
CVarRef key = it.first();
if (!key.isString()) continue;
std::string name = key.toCStrRef().data();
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(ar, ar, loc, value);
TypePtr t =
value.isNull() ? Type::Null :
value.isBoolean() ? Type::Boolean :
value.isInteger() ? Type::Int64 :
value.isDouble() ? Type::Double :
value.isArray() ? Type::Array : Type::Variant;
cns->add(key.toCStrRef().data(), t, e, ar, e);
}
for (int i = 0, n = NumGlobalNames(); i < n; ++i) {
ar->getVariables()->add(GlobalNames[i], Type::Variant, false, ar,
ConstructPtr(), ModifierExpressionPtr());
}
if (!extOnly) {
Array constants = ClassInfo::GetSystemConstants();
LocationPtr loc(new Location);
for (ArrayIter it = constants.begin(); it; ++it) {
CVarRef key = it.first();
if (!key.isString()) continue;
std::string name = key.toCStrRef().data();
if (s_constants->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);
TypePtr t =
value.isNull() ? Type::Null :
value.isBoolean() ? Type::Boolean :
value.isInteger() ? Type::Int64 :
value.isDouble() ? Type::Double :
value.isArray() ? Type::Array : Type::Variant;
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);
s_constants->add(key.toCStrRef().data(), t, e, ar2, e);
// Systemlib files were all parsed by hphp_process_init
const StringToFileScopePtrMap &files = ar->getAllFiles();
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);
}
}
s_variables = ar2->getVariables();
for (int i = 0, n = NumGlobalNames(); i < n; ++i) {
s_variables->add(GlobalNames[i], Type::Variant, false, ar,
ConstructPtr(), ModifierExpressionPtr());
const auto& functions = file.second->getFunctions();
for (const auto& func : functions) {
func.second->setSystem();
ar->addSystemFunction(func.second);
FunctionScope::RecordFunctionInfo(func.first, func.second);
}
}
s_constants->setDynamic(ar, "SID", true);
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::ScannerType);
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);
for (StringToFunctionScopePtrMap::const_iterator it = s_functions.begin();
it != s_functions.end(); ++it) {
if (functions.find(it->first) == functions.end()) {
functions[it->first] = it->second;
FunctionScope::RecordFunctionInfo(it->first, it->second);
}
}
}
void BuiltinSymbols::LoadClasses(AnalysisResultPtr ar,
StringToClassScopePtrMap &classes) {
assert(Loaded);
classes.insert(s_classes.begin(), s_classes.end());
// we are adding these builtin functions, so that user-defined functions
// will not overwrite them with their own file and line number information
for (StringToClassScopePtrMap::const_iterator iter =
s_classes.begin(); iter != s_classes.end(); ++iter) {
const StringToFunctionScopePtrMap &funcs = iter->second->getFunctions();
for (StringToFunctionScopePtrMap::const_iterator iter =
funcs.begin(); iter != funcs.end(); ++iter) {
FunctionScope::RecordFunctionInfo(iter->first, iter->second);
}
}
}
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;
@@ -596,7 +410,6 @@ void BuiltinSymbols::LoadSuperGlobals() {
}
bool BuiltinSymbols::IsSuperGlobal(const std::string &name) {
if (NoSuperGlobals) return false;
return s_superGlobals.find(name) != s_superGlobals.end();
}
+29 -46
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,28 +14,29 @@
+----------------------------------------------------------------------+
*/
#ifndef __BUILTIN_SYMBOLS_H__
#define __BUILTIN_SYMBOLS_H__
#ifndef incl_HPHP_BUILTIN_SYMBOLS_H_
#define incl_HPHP_BUILTIN_SYMBOLS_H_
#include <compiler/hphp.h>
#include <util/string_bag.h>
#include "hphp/compiler/hphp.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 bool NoSuperGlobals; // for SystemCPP bootstraping only
static AnalysisResultPtr s_systemAr;
static bool Load(AnalysisResultPtr ar, bool extOnly = false);
static bool Load(AnalysisResultPtr ar);
static void LoadFunctions(AnalysisResultPtr ar,
StringToFunctionScopePtrMap &functions);
@@ -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,48 +56,35 @@ 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 const char *const GlobalNames[];
static int NumGlobalNames();
private:
static StringBag s_strings;
static const char *ExtensionFunctions[];
static const char *ExtensionClasses[];
static const char *ExtensionConsts[];
static const char *ExtensionDeclaredDynamic[];
static const char *SystemClasses[];
static AnalysisResultPtr LoadGlobalSymbols(const char *fileName);
static void Parse(AnalysisResultPtr ar,
const std::string& phpBaseName,
const std::string& phpFileName);
static StringToTypePtrMap s_superGlobals;
static std::set<std::string> s_declaredDynamic;
static void *s_handle_main;
static bool LoadSepExtensionSymbols(AnalysisResultPtr ar,
const std::string &name,
const std::string &soname);
static TypePtr ParseType(const char **&p);
static void ParseExtFunctions(AnalysisResultPtr ar, const char **p,
bool sep);
static void ParseExtConsts(AnalysisResultPtr ar, const char **p, bool sep);
static void ParseExtClasses(AnalysisResultPtr ar, const char **p, bool sep);
static void ParseExtDynamics(AnalysisResultPtr ar, const char **p, bool sep);
static FunctionScopePtr ParseExtFunction(AnalysisResultPtr ar,
const char** &p, bool method = false);
static FunctionScopePtr ParseHelperFunction(AnalysisResultPtr ar,
const char** &p);
static FunctionScopePtr ImportFunctionScopePtr(AnalysisResultPtr ar,
ClassInfo *cls,
ClassInfo::MethodInfo *method);
static void ImportExtFunctions(AnalysisResultPtr ar,
ClassInfo *cls);
static void ImportExtMethods(AnalysisResultPtr ar,
FunctionScopePtrVec &vec,
ClassInfo *cls);
static void ImportExtProperties(AnalysisResultPtr ar,
VariableTablePtr dest,
ClassInfo *cls);
static void ImportExtConstants(AnalysisResultPtr ar,
ConstantTablePtr dest,
ClassInfo *cls);
static ClassScopePtr ImportClassScopePtr(AnalysisResultPtr ar,
ClassInfo *cls);
static void ImportExtClasses(AnalysisResultPtr ar);
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // __BUILTIN_SYMBOLS_H__
#endif // incl_HPHP_BUILTIN_SYMBOLS_H_
+181 -12
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,17 +14,18 @@
+----------------------------------------------------------------------+
*/
#include <stdarg.h>
#include <compiler/code_generator.h>
#include <compiler/statement/statement_list.h>
#include <compiler/option.h>
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/variable_table.h>
#include <util/util.h>
#include <util/hash.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>
#include <boost/scoped_array.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();
}
+49 -24
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,22 +14,26 @@
+----------------------------------------------------------------------+
*/
#ifndef __CODE_GENERATOR_H__
#define __CODE_GENERATOR_H__
#ifndef incl_HPHP_CODE_GENERATOR_H_
#define incl_HPHP_CODE_GENERATOR_H_
#include <compiler/hphp.h>
#include "hphp/compiler/hphp.h"
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 {
@@ -131,8 +136,8 @@ public:
public:
CodeGenerator() {} // only for creating a dummy code generator
CodeGenerator(std::ostream *primary, Output output = PickledPHP,
const std::string *filename = nullptr);
explicit CodeGenerator(std::ostream *primary, Output output = PickledPHP,
const std::string *filename = nullptr);
/**
* ...if it was passed in from constructor.
@@ -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];
@@ -308,28 +338,23 @@ private:
public: void print(const char *msg, bool indent = true);
private:
void print(const char *fmt, va_list ap);
void print(const char *fmt, va_list ap) ATTRIBUTE_PRINTF(2,0);
void printSubstring(const char *start, int length);
void printIndent();
std::string getFormattedName(const std::string &file);
};
#define STR(x) #x
#define XSTR(x) STR(x)
#define FLANN(stream,func,nl) (Option::FlAnnotate ? \
stream.printf("/* %s:" XSTR(__LINE__) "*/" nl, __func__): \
void()), stream.func
#define cg_printf FLANN(cg,printf,"")
#define m_cg_printf FLANN(m_cg,printf,"")
#define cg_print FLANN(cg,print,"")
#define m_cg_print FLANN(m_cg,print,"")
#define cg_indentBegin FLANN(cg,indentBegin,"")
#define m_cg_indentBegin FLANN(m_cg,indentBegin,"")
#define cg_indentEnd FLANN(cg,indentEnd,"")
#define m_cg_indentEnd FLANN(m_cg,indentEnd,"")
#define cg_printInclude FLANN(cg,printInclude,"\n")
#define cg_printString FLANN(cg,printString,"")
#define cg_printf cg.printf
#define m_cg_printf m_cg.printf
#define cg_print cg.print
#define m_cg_print m_cg.print
#define cg_indentBegin cg.indentBegin
#define m_cg_indentBegin m_cg.indentBegin
#define cg_indentEnd cg.indentEnd
#define m_cg_indentEnd cg.indentEnd
#define cg_printInclude cg.printInclude
#define cg_printString cg.printString
///////////////////////////////////////////////////////////////////////////////
}
#endif // __CODE_GENERATOR_H__
#endif // incl_HPHP_CODE_GENERATOR_H_
+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_
+87 -150
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,43 +14,45 @@
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/compiler.h"
#include "hphp/compiler/package.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/alias_manager.h"
#include "hphp/compiler/analysis/code_error.h"
#include "hphp/compiler/analysis/emitter.h"
#include "hphp/compiler/analysis/type.h"
#include "hphp/compiler/analysis/symbol_table.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/compiler/json.h"
#include "hphp/util/logger.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/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/vm/repo.h"
#include "hphp/system/systemlib.h"
#include "hphp/util/repo-schema.h"
#include "hphp/hhvm/process-init.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <dlfcn.h>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/parsers.hpp>
#include <compiler/package.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/alias_manager.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/emitter.h>
#include <compiler/analysis/type.h>
#include <util/json.h>
#include <util/logger.h>
#include <compiler/analysis/symbol_table.h>
#include <compiler/option.h>
#include <compiler/parser/parser.h>
#include <compiler/builtin_symbols.h>
#include <util/db_conn.h>
#include <util/exception.h>
#include <util/process.h>
#include <util/util.h>
#include <util/timer.h>
#include <util/hdf.h>
#include <util/async_func.h>
#include <runtime/base/program_functions.h>
#include <runtime/base/memory/smart_allocator.h>
#include <runtime/base/externals.h>
#include <runtime/base/thread_init_fini.h>
#include <runtime/vm/repo.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dlfcn.h>
#include <system/lib/systemlib.h>
#include <compiler/compiler.h>
#include "hhvm/process_init.h"
using namespace boost::program_options;
using std::cout;
@@ -61,7 +63,6 @@ struct CompilerOptions {
string target;
string format;
string outputDir;
string outputFile;
string syncDir;
vector<string> config;
string configDir;
@@ -82,8 +83,6 @@ struct CompilerOptions {
vector<string> cfiles;
vector<string> cmodules;
bool parseOnDemand;
vector<string> parseOnDemandDirs; // parse these directories on-demand
// when parseOnDemand=false
string program;
string programArgs;
string branch;
@@ -92,21 +91,15 @@ struct CompilerOptions {
bool keepTempDir;
string dbStats;
bool noTypeInference;
bool noMinInclude;
bool noMetaInfo;
int logLevel;
bool force;
int clusterCount;
int optimizeLevel;
string filecache;
string javaRoot;
bool dump;
string docjson;
bool coredump;
bool nofork;
bool fl_annotate;
string optimizations;
string ppp;
};
///////////////////////////////////////////////////////////////////////////////
@@ -124,7 +117,8 @@ public:
struct stat sb;
stat(m_name, &sb);
Logger::Info("%dMB %s saved", (int64_t)sb.st_size/(1024*1024), m_name);
Logger::Info("%" PRId64" MB %s saved",
(int64_t)sb.st_size/(1024*1024), m_name);
}
private:
@@ -146,7 +140,6 @@ int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
AsyncFileCacheSaver &fcThread);
int runTargetCheck(const CompilerOptions &po, AnalysisResultPtr ar,
AsyncFileCacheSaver &fcThread);
int buildTarget(const CompilerOptions &po);
int runTarget(const CompilerOptions &po);
///////////////////////////////////////////////////////////////////////////////
@@ -157,6 +150,10 @@ int compiler_main(int argc, char **argv) {
try {
Hdf empty;
RuntimeOption::Load(empty);
initialize_repo();
// we need to initialize pcre cache table very early
pcre_init();
CompilerOptions po;
#ifdef FACEBOOK
@@ -195,6 +192,10 @@ int compiler_main(int argc, char **argv) {
return ret;
} catch (Exception &e) {
Logger::Error("Exception: %s\n", e.getMessage().c_str());
} catch (const FailedAssertion& fa) {
fa.print();
StackTraceNoHeap::AddExtraLogging("Assertion failure", fa.summary);
abort();
} catch (std::exception &e) {
Logger::Error("std::exception: %s\n", e.what());
} catch (...) {
@@ -226,9 +227,6 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
" <any combination of them by any separator>; \n"
"hhbc: binary (default) | text; \n"
"run: cluster (default) | file")
("cluster-count", value<int>(&po.clusterCount)->default_value(0),
"Cluster by file sizes and output roughly these many number of files. "
"Use 0 for no clustering.")
("input-dir", value<string>(&po.inputDir), "input directory")
("program", value<string>(&po.program)->default_value("program"),
"final program name to use")
@@ -275,7 +273,6 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
("branch", value<string>(&po.branch), "SVN branch")
("revision", value<int>(&po.revision), "SVN revision")
("output-dir,o", value<string>(&po.outputDir), "output directory")
("output-file", value<string>(&po.outputFile), "output file")
("sync-dir", value<string>(&po.syncDir),
"Files will be created in this directory first, then sync with output "
"directory without overwriting identical files. Great for incremental "
@@ -292,13 +289,6 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
("no-type-inference",
value<bool>(&po.noTypeInference)->default_value(false),
"turn off type inference for C++ code generation")
("no-min-include",
value<bool>(&po.noMinInclude)->default_value(false),
"turn off minimium include analysis when target is \"analyze\"")
("no-meta-info",
value<bool>(&po.noMetaInfo)->default_value(false),
"do not generate class map, function jump table and macros "
"when generating code; good for demo purposes")
("config,c", value<vector<string> >(&po.config)->composing(),
"config file name")
("config-dir", value<string>(&po.configDir),
@@ -330,22 +320,11 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
value<bool>(&po.nofork)->default_value(false),
"forking is needed for large compilation to release memory before g++"
"compilation. turning off forking can help gdb debugging.")
("fl-annotate",
value<bool>(&po.fl_annotate)->default_value(false),
"Annotate emitted source with compiler file-line info")
("opts",
value<string>(&po.optimizations)->default_value(""),
"Set optimizations to enable/disable")
("ppp",
value<string>(&po.ppp)->default_value(""),
"Preprocessed partition configuration. To speed up distcc compilation, "
"bin/ppp.php can pre-compute better partition between different .cpp "
"files according to preprocessed file sizes, instead of original file "
"sizes (default). Run bin/ppp.php to generate an HDF configuration file "
"to specify here.")
("compiler-id", "display the git hash for the compiler id")
("repo-schema", "display the repo schema id used by this app")
("taint-status", "check if the compiler was built with taint enabled")
;
positional_options_description p;
@@ -355,7 +334,7 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
store(command_line_parser(argc, argv).options(desc).positional(p).run(),
vm);
notify(vm);
} catch (unknown_option e) {
} catch (const unknown_option& e) {
Logger::Error("Error in command line: %s\n\n", e.what());
cout << desc << "\n";
return -1;
@@ -365,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
@@ -379,11 +358,11 @@ 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: " << VM::Repo::kSchemaId << "\n";
cout << "Repo schema: " << kRepoSchemaId << "\n";
return 1;
}
@@ -393,14 +372,7 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
}
if (vm.count("repo-schema")) {
cout << VM::Repo::kSchemaId << "\n";
return 1;
}
if (vm.count("taint-status")) {
#ifdef TAINTED
cout << TAINTED << "\n";
#endif
cout << kRepoSchemaId << "\n";
return 1;
}
@@ -420,8 +392,6 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
Logger::LogLevel = Logger::LogInfo;
}
Option::FlAnnotate = po.fl_annotate;
Hdf config;
for (vector<string>::const_iterator it = po.config.begin();
it != po.config.end(); ++it) {
@@ -474,12 +444,10 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
}
if (po.target == "hhbc" || po.target == "run") {
Option::OutputHHBC = true;
Option::AnalyzePerfectVirtuals = false;
}
Option::ProgramName = po.program;
Option::PreprocessedPartitionConfig = po.ppp;
if (po.format.empty()) {
if (po.target == "php") {
@@ -504,11 +472,7 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
}
if (po.optimizeLevel == -1) {
if (Option::OutputHHBC) {
po.optimizeLevel = 1;
} else {
po.optimizeLevel = 1;
}
po.optimizeLevel = 1;
}
// we always do pre/post opt no matter the opt level
@@ -517,11 +481,11 @@ int prepareOptions(CompilerOptions &po, int argc, char **argv) {
if (po.optimizeLevel == 0) {
// --optimize-level=0 is equivalent to --opts=none
po.optimizations = "none";
if (Option::OutputHHBC) {
Option::ParseTimeOpts = false;
}
Option::ParseTimeOpts = false;
}
initialize_hhbbc_options();
return 0;
}
@@ -563,9 +527,7 @@ int process(const CompilerOptions &po) {
Package package(po.inputDir.c_str());
ar = package.getAnalysisResult();
if (po.target == "hhbc" || po.target == "run") {
hhbcTargetInit(po, ar);
}
hhbcTargetInit(po, ar);
std::string errs;
if (!AliasManager::parseOptimizations(po.optimizations, errs)) {
@@ -580,17 +542,19 @@ int process(const CompilerOptions &po) {
bool isPickledPHP = (po.target == "php" && po.format == "pickled");
if (!isPickledPHP) {
if (!BuiltinSymbols::Load(ar,
po.target == "hhbc" && !Option::WholeProgram)) {
return false;
}
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) {
BuiltinSymbols::NoSuperGlobals = false;
// We're trying to produce the same bytecode as runtime parsing.
// There's nothing to do.
} else {
ar->loadBuiltins();
}
if (!Option::SystemGen) {
hphp_process_init();
if (!BuiltinSymbols::Load(ar)) {
return false;
}
}
}
@@ -638,6 +602,7 @@ int process(const CompilerOptions &po) {
return 1;
}
if (Option::WholeProgram || po.target == "analyze") {
Timer timer(Timer::WallTime, "analyzeProgram");
ar->analyzeProgram();
}
}
@@ -691,7 +656,7 @@ int process(const CompilerOptions &po) {
int runId = package.saveStatsToDB(server, seconds, po.branch,
po.revision);
package.commitStats(server, runId);
} catch (DatabaseException e) {
} catch (const DatabaseException& e) {
Logger::Error("%s", e.what());
}
} else {
@@ -716,7 +681,7 @@ int lintTarget(const CompilerOptions &po) {
for (unsigned int i = 0; i < po.inputs.size(); i++) {
string filename = po.inputDir + "/" + po.inputs[i];
try {
Scanner scanner(filename.c_str(), Option::ScannerType);
Scanner scanner(filename.c_str(), Option::GetScannerType());
Compiler::Parser parser(scanner, filename.c_str(),
AnalysisResultPtr(new AnalysisResult()));
if (!parser.parse()) {
@@ -842,11 +807,16 @@ 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
RuntimeOption::RepoCommit = false;
}
int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
@@ -878,7 +848,7 @@ int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
/* without this, emitClass allows classes with interfaces to be
hoistable */
SystemLib::s_inited = true;
RuntimeOption::RepoCommit = true;
Option::AutoInline = -1;
if (po.optimizeLevel > 0) {
@@ -905,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;
}
@@ -919,42 +889,6 @@ int hhbcTarget(const CompilerOptions &po, AnalysisResultPtr ar,
///////////////////////////////////////////////////////////////////////////////
int buildTarget(const CompilerOptions &po) {
const char *HPHP_HOME = getenv("HPHP_HOME");
if (!HPHP_HOME || !*HPHP_HOME) {
throw Exception("Environment variable HPHP_HOME is not set.");
}
string cmd = string(HPHP_HOME) + "/hphp/legacy/run.sh";
string flags;
if (getenv("RELEASE")) flags += "RELEASE=1 ";
if (getenv("SHOW_LINK")) flags += "SHOW_LINK=1 ";
if (getenv("SHOW_COMPILE")) flags += "SHOW_COMPILE=1 ";
if (po.format == "lib") flags += "HPHP_BUILD_LIBRARY=1 ";
const char *argv[] = {"", po.outputDir.c_str(),
po.program.c_str(), flags.c_str(), nullptr};
if (getenv("SHOW_COMPILE")) {
Logger::Info ("Compile command: %s %s %s", po.outputDir.c_str(),
po.program.c_str(), flags.c_str());
}
Timer timer(Timer::WallTime, "compiling and linking CPP files");
string out, err;
bool ret = Process::Exec(cmd.c_str(), argv, nullptr, out, &err);
if (getenv("SHOW_COMPILE")) {
Logger::Info("%s", out.c_str());
} else {
Logger::Verbose("%s", out.c_str());
}
if (!err.empty()) {
Logger::Error("%s", err.c_str());
}
if (!ret) {
return 1;
}
return 0;
}
int runTargetCheck(const CompilerOptions &po, AnalysisResultPtr ar,
AsyncFileCacheSaver &fcThread) {
// generate code
@@ -984,17 +918,20 @@ 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;
cmd += string(" --file ") +
(po.inputs.size() == 1 ? po.inputs[0] : "") + po.programArgs;
Logger::Info("running executable %s...", cmd.c_str());
(po.inputs.size() == 1 ? po.inputs[0] : "") +
" " + po.programArgs;
Logger::Info("running executable: %s", cmd.c_str());
ret = Util::ssystem(cmd.c_str());
if (ret && ret != -1) ret = 1;
+1 -1
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
+32 -17
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,21 +14,21 @@
+----------------------------------------------------------------------+
*/
#include <compiler/construct.h>
#include <compiler/parser/parser.h>
#include <util/util.h>
#include "hphp/compiler/construct.h"
#include "hphp/compiler/parser/parser.h"
#include "hphp/util/util.h"
#include <compiler/analysis/file_scope.h>
#include <compiler/analysis/function_scope.h>
#include <compiler/analysis/class_scope.h>
#include <compiler/analysis/analysis_result.h>
#include <compiler/analysis/ast_walker.h>
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/class_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/ast_walker.h"
#include <compiler/statement/function_statement.h>
#include "hphp/compiler/statement/function_statement.h"
#include <compiler/expression/simple_function_call.h>
#include <compiler/expression/simple_variable.h>
#include <compiler/expression/closure_expression.h>
#include "hphp/compiler/expression/simple_function_call.h"
#include "hphp/compiler/expression/simple_variable.h"
#include "hphp/compiler/expression/closure_expression.h"
#include <iomanip>
using namespace HPHP;
@@ -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);
}
@@ -454,7 +454,8 @@ private:
void Construct::dump(int spc, AnalysisResultConstPtr ar) {
ConstructDumper cd(spc, ar);
cd.walk(ConstructRawPtr(this), ConstructRawPtr(), ConstructRawPtr());
cd.walk(AstWalkerStateVec(ConstructRawPtr(this)),
ConstructRawPtr(), ConstructRawPtr());
}
void Construct::dump(int spc, AnalysisResultConstPtr ar, bool functionOnly,
@@ -468,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());
}
+24 -15
Ver Arquivo
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,13 +14,13 @@
+----------------------------------------------------------------------+
*/
#ifndef __CONSTRUCT_H__
#define __CONSTRUCT_H__
#ifndef incl_HPHP_CONSTRUCT_H_
#define incl_HPHP_CONSTRUCT_H_
#include <util/json.h>
#include <compiler/code_generator.h>
#include <compiler/analysis/code_error.h>
#include <compiler/analysis/block_scope.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"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -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);
@@ -178,7 +178,10 @@ public:
return m_blockScope->getContainingClass();
}
void resetScope(BlockScopeRawPtr scope, bool resetOrigScope=false);
void parseTimeFatal(Compiler::ErrorType error, const char *fmt, ...);
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;
@@ -186,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);
@@ -242,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.
*/
@@ -314,7 +323,7 @@ public:
int getLocalEffects() const { return m_localEffects; }
virtual void effectsCallback() = 0;
protected:
LocalEffectsContainer(Construct::Effect localEffect) :
explicit LocalEffectsContainer(Construct::Effect localEffect) :
m_localEffects(localEffect) {}
LocalEffectsContainer() :
m_localEffects(0) {}
@@ -333,4 +342,4 @@ protected:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __CONSTRUCT_H__
#endif // incl_HPHP_CONSTRUCT_H_
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,17 +14,18 @@
+----------------------------------------------------------------------+
*/
#include <compiler/expression/array_element_expression.h>
#include <compiler/expression/simple_variable.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/analysis/variable_table.h>
#include <compiler/analysis/code_error.h>
#include <compiler/option.h>
#include <compiler/expression/static_member_expression.h>
#include <compiler/analysis/function_scope.h>
#include <util/parser/hphp.tab.hpp>
#include <runtime/base/complex_types.h>
#include <runtime/base/builtin_functions.h>
#include "hphp/compiler/expression/array_element_expression.h"
#include "hphp/compiler/expression/simple_variable.h"
#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/parser/hphp.tab.hpp"
#include "hphp/runtime/base/complex-types.h"
#include "hphp/runtime/base/builtin-functions.h"
using namespace HPHP;
@@ -167,16 +168,6 @@ void ArrayElementExpression::analyzeProgram(AnalysisResultPtr ar) {
m_variable->analyzeProgram(ar);
if (m_offset) m_offset->analyzeProgram(ar);
if (ar->getPhase() == AnalysisResult::AnalyzeFinal) {
if (!m_global && (m_context & AccessContext) &&
!(m_context & (LValue|RefValue|DeepReference|
UnsetContext|RefParameter|InvokeArgument))) {
TypePtr type = m_variable->getActualType();
if (!type ||
(!type->is(Type::KindOfString) && !type->is(Type::KindOfArray))) {
FunctionScopePtr scope = getFunctionScope();
if (scope && !needsCSE()) scope->setNeedsRefTemp();
}
}
if (m_global) {
if (getContext() & (LValue|RefValue|DeepReference)) {
setContext(NoLValueWrapper);
@@ -191,8 +182,6 @@ void ArrayElementExpression::analyzeProgram(AnalysisResultPtr ar) {
shared_from_this());
}
}
FunctionScopePtr scope = getFunctionScope();
if (scope) scope->setNeedsCheckMem();
} else {
TypePtr at(m_variable->getActualType());
TypePtr et(m_variable->getExpectedType());
@@ -229,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);
@@ -257,6 +246,14 @@ ExpressionPtr ArrayElementExpression::preOptimize(AnalysisResultConstPtr ar) {
return replaceValue(makeConstant(ar, "null"));
}
if (m_offset->isScalar() && m_offset->getScalarValue(o)) {
if (v.isString()) {
if (!o.isInteger() ||
o.toInt64Val() < 0 ||
o.toInt64Val() >= v.toCStrRef().size()) {
// warnings should be raised...
return ExpressionPtr();
}
}
try {
g_context->setThrowAllErrors(true);
Variant res = v.rvalAt(
@@ -392,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
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,10 +14,10 @@
+----------------------------------------------------------------------+
*/
#ifndef __ARRAY_ELEMENT_EXPRESSION_H__
#define __ARRAY_ELEMENT_EXPRESSION_H__
#ifndef incl_HPHP_ARRAY_ELEMENT_EXPRESSION_H_
#define incl_HPHP_ARRAY_ELEMENT_EXPRESSION_H_
#include <compiler/expression/expression.h>
#include "hphp/compiler/expression/expression.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
@@ -70,4 +70,4 @@ private:
///////////////////////////////////////////////////////////////////////////////
}
#endif // __ARRAY_ELEMENT_EXPRESSION_H__
#endif // incl_HPHP_ARRAY_ELEMENT_EXPRESSION_H_
@@ -2,7 +2,7 @@
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
| 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 |
@@ -14,10 +14,11 @@
+----------------------------------------------------------------------+
*/
#include <compiler/expression/array_pair_expression.h>
#include <compiler/expression/scalar_expression.h>
#include <compiler/expression/unary_op_expression.h>
#include <util/parser/hphp.tab.hpp>
#include "hphp/compiler/expression/array_pair_expression.h"
#include "hphp/compiler/expression/scalar_expression.h"
#include "hphp/compiler/expression/unary_op_expression.h"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/parser/hphp.tab.hpp"
using namespace HPHP;
@@ -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

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais